问:
React-Hook Form with useFieldArray: TextField value does not show up in the console. How can I fix it?
I wanted to enter the word Product but when I submit it, it does not show up in the console.

What shows up in the console:

As you can see here, the word Product does not appear in the console. Any idea on how I can solve this?

This is the codesandbox link: https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/index.js

this is the fieldArray.js where the input fields for products is

```<code>import React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>
      <ul>
        {fields.map((item, index) => {
          return (
            <li key={item.id}>
              {/* <select
                ref={register()}
                name={`test[${index}].name`}
                defaultValue={item.name}
              >
                <option value="">Select</option>
                <option value="10">ItemA</option>
                <option value="20">ItemB</option>
              </select> */}
              {/* {index + 1}  to show the qty */}
              <TextField
                name={`test[${index}].name`}
                refer={register()}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />
            </li>
          );
        })}
      </ul>

      <section>
        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>
      </section>

      <span className="counter">Render Count: {renderCount}</span>
    </>
  );
}
</code>```

答:
you can change it try way:

fieldArray.js

```<code><TextField
  name={`test[${index}].nestedArray[${index}].product`}
  inputRef={register({ required: true })}
  defaultValue={item.name}
/>;
</code>```

Body:
I wanted to enter the word Product but when I submit it, it does not show up in the console.

What shows up in the console:

As you can see here, the word Product does not appear in the console. Any idea on how I can solve this?

This is the codesandbox link: https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/index.js

this is the fieldArray.js where the input fields for products is

import React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>

        {fields.map((item, index) => {
          return (

              {/* <select
                ref={register()}
                name={`test[${index}].name`}
                defaultValue={item.name}
              >
                <option value="">Select</option>
                <option value="10">ItemA</option>
                <option value="20">ItemB</option>
              </select> */}
              {/* {index + 1}  to show the qty */}
              <TextField
                name={`test[${index}].name`}
                refer={register()}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />

          );
        })}

        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>

      Render Count: {renderCount}
    </>
  );
}

Body:
you can change it try way:

fieldArray.js

<TextField
  name={`test[${index}].nestedArray[${index}].product`}
  inputRef={register({ required: true })}
  defaultValue={item.name}
/>;


来源: stackexchange

问:
How can I keep the user logged in when I reopens the app android studio
I have made the app and using the sqlite database I stored the details in the database. But now I want to verify and keep the user logged in and if the user is logged in directly next activity should be opened. Can any one help me with that.

This is the Login activity:

```<code>     private TextInputEditText mobileedittext,passwordedittext;
private DBase dBase;
private User user;

public static String PREFS = "prefsFile";
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    initview();
    initListener();
    initObject();

}

private void initview(){
    layout = findViewById(R.id.login_layout);

    lay_login_mobile = findViewById(R.id.lay_login_mobile);
    lay_login_password = findViewById(R.id.lay_login_password);

    mobileedittext = findViewById(R.id.loginmobile_edit);
    passwordedittext = findViewById(R.id.loginpassword_edit);

    b1 = findViewById(R.id.Loginbtn);

}

private void initListener(){
    b1.setOnClickListener(v -> {

        String mob = mobileedittext.getText().toString();
        String pass = passwordedittext.getText().toString();
        if(mob.equals("") || pass.equals("")){
            Toast.makeText(Login.this, "Enter all the fields", Toast.LENGTH_SHORT).show();

        } else {
            if(!dBase.checkUser(mobileedittext.getText().toString(),passwordedittext.getText().toString())) {
                Toast.makeText(Login.this, "Invalid Credentials. Check Mobile number or Password", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(Login.this, "Login Successful", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Login.this, BabyDetails.class);
                startActivity(intent);
            }
        }
        SharedPreferences sharedPreferences = getSharedPreferences(Login.PREFS,0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("hasLoggedIn",true);
        editor.commit();
    });
}

private void initObject(){
    dBase = new DBase(Login.this);
    user = new User();
}
</code>```

The Main Activity(Splash screen) :

```<code>  ProgressBar pb;
Handler h = new Handler();
int count = 0;
Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pb = (ProgressBar) findViewById(R.id.progressBar);

    timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            count++;
            pb.setProgress(count);
            if(count == 99){
                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        SharedPreferences sharedPreferences = getSharedPreferences(Login.PREFS,0);
                        Boolean hasLoggedIn = sharedPreferences.getBoolean("hasLoggedIn",false);

                        if(hasLoggedIn){
                            Intent intent = new Intent(MainPage.this,BabyDetails.class);
                            startActivity(intent);
                            finish();
                        }
                        else {
                            Intent i = new Intent(MainPage.this, Login.class);
                            startActivity(i);
                            finish();
                        }

                    }
                },100);

            }
        }
    };
    timer.schedule(timerTask,0,100);
</code>```

the database contains the checkuser function it check if the user is already existed but now it should check if the user is logged in also :

```<code>        private static final String DATABASE_NAME = "UserDetails.db";
private static final String TABLE_USER = "User";
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_MOBILE = "mobile";
private static final String COLUMN_USER_EMAIL = "email";
private static final String COLUMN_USER_MOTHERNAME = "mother_name";
private static final String COLUMN_USER_FATHERNAME = "father_name";
private static final String COLUMN_USER_PASSWORD = "password";
private static final String COLUMN_USER_CONFIRM_PASSWORD = "confirm_password";

private String CREATE_USER_TABLE = "CREATE TABLE  "+ TABLE_USER + "(" +
        COLUMN_USER_ID +" INTEGER PRIMARY KEY AUTOINCREMENT , " + COLUMN_USER_MOBILE + " TEXT," + COLUMN_USER_EMAIL + " TEXT, "
        + COLUMN_USER_MOTHERNAME + " TEXT, " + COLUMN_USER_FATHERNAME + " TEXT, " +
        COLUMN_USER_PASSWORD + " TEXT, " + COLUMN_USER_CONFIRM_PASSWORD + " TEXT " + ")";

private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;

public DBase(Context context){
    super(context,DATABASE_NAME,null,DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_USER_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     db.execSQL(DROP_USER_TABLE);
    onCreate(db);
}

public void addUser(User user){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_USER_MOBILE,user.getMobile());
    values.put(COLUMN_USER_EMAIL,user.getEmail());
    values.put(COLUMN_USER_MOTHERNAME,user.getMothername());
    values.put(COLUMN_USER_FATHERNAME,user.getFathername());
    values.put(COLUMN_USER_PASSWORD,user.getPass());
    values.put(COLUMN_USER_CONFIRM_PASSWORD,user.getConpass());
    db.insert(TABLE_USER,null,values);
    db.close();
}
 public boolean checkUser(String mobile, String pass ){

    String[] column = {COLUMN_USER_ID};
    SQLiteDatabase db= this.getReadableDatabase();
    String selection = COLUMN_USER_MOBILE+ " = ? " + " AND " + COLUMN_USER_PASSWORD + " = ? ";
    String[] selectionArgs = {mobile, pass};

    int cursorCount;
    try (Cursor cursor = db.query(TABLE_USER, column, selection, selectionArgs, null, null, null)) {
        cursorCount = cursor.getCount();
    }
    db.close();
    if(cursorCount > 0){
        return true;
    }

    return false;
}
</code>```

Can anybody provide the necessary codes for it and explain it also .

Thank you

答:
When You Login In LoginActivity Just Set SharedPreference

```<code>   public static final String MyPREFERENCES = "MyPrefs" ;
   public static final String Name = "nameKey";
</code>```

In OnCreate()

```<code>SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
</code>```

And In MainActivity

```<code>  SharedPreferences sharedpreferences = getSharedPreferences(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = sharedpreferences.edit();
  editor.clear();
  editor.commit();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have made the app and using the sqlite database I stored the details in the database. But now I want to verify and keep the user logged in and if the user is logged in directly next activity should be opened. Can any one help me with that.

This is the Login activity:

     private TextInputEditText mobileedittext,passwordedittext;
private DBase dBase;
private User user;

public static String PREFS = "prefsFile";
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    initview();
    initListener();
    initObject();

}

private void initview(){
    layout = findViewById(R.id.login_layout);

    lay_login_mobile = findViewById(R.id.lay_login_mobile);
    lay_login_password = findViewById(R.id.lay_login_password);

    mobileedittext = findViewById(R.id.loginmobile_edit);
    passwordedittext = findViewById(R.id.loginpassword_edit);

    b1 = findViewById(R.id.Loginbtn);

}

private void initListener(){
    b1.setOnClickListener(v -> {

        String mob = mobileedittext.getText().toString();
        String pass = passwordedittext.getText().toString();
        if(mob.equals("") || pass.equals("")){
            Toast.makeText(Login.this, "Enter all the fields", Toast.LENGTH_SHORT).show();

        } else {
            if(!dBase.checkUser(mobileedittext.getText().toString(),passwordedittext.getText().toString())) {
                Toast.makeText(Login.this, "Invalid Credentials. Check Mobile number or Password", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(Login.this, "Login Successful", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Login.this, BabyDetails.class);
                startActivity(intent);
            }
        }
        SharedPreferences sharedPreferences = getSharedPreferences(Login.PREFS,0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("hasLoggedIn",true);
        editor.commit();
    });
}

private void initObject(){
    dBase = new DBase(Login.this);
    user = new User();
}

The Main Activity(Splash screen) :

  ProgressBar pb;
Handler h = new Handler();
int count = 0;
Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pb = (ProgressBar) findViewById(R.id.progressBar);

    timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            count++;
            pb.setProgress(count);
            if(count == 99){
                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        SharedPreferences sharedPreferences = getSharedPreferences(Login.PREFS,0);
                        Boolean hasLoggedIn = sharedPreferences.getBoolean("hasLoggedIn",false);

                        if(hasLoggedIn){
                            Intent intent = new Intent(MainPage.this,BabyDetails.class);
                            startActivity(intent);
                            finish();
                        }
                        else {
                            Intent i = new Intent(MainPage.this, Login.class);
                            startActivity(i);
                            finish();
                        }

                    }
                },100);

            }
        }
    };
    timer.schedule(timerTask,0,100);

the database contains the checkuser function it check if the user is already existed but now it should check if the user is logged in also :

        private static final String DATABASE_NAME = "UserDetails.db";
private static final String TABLE_USER = "User";
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_MOBILE = "mobile";
private static final String COLUMN_USER_EMAIL = "email";
private static final String COLUMN_USER_MOTHERNAME = "mother_name";
private static final String COLUMN_USER_FATHERNAME = "father_name";
private static final String COLUMN_USER_PASSWORD = "password";
private static final String COLUMN_USER_CONFIRM_PASSWORD = "confirm_password";

private String CREATE_USER_TABLE = "CREATE TABLE  "+ TABLE_USER + "(" +
        COLUMN_USER_ID +" INTEGER PRIMARY KEY AUTOINCREMENT , " + COLUMN_USER_MOBILE + " TEXT," + COLUMN_USER_EMAIL + " TEXT, "
        + COLUMN_USER_MOTHERNAME + " TEXT, " + COLUMN_USER_FATHERNAME + " TEXT, " +
        COLUMN_USER_PASSWORD + " TEXT, " + COLUMN_USER_CONFIRM_PASSWORD + " TEXT " + ")";

private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;

public DBase(Context context){
    super(context,DATABASE_NAME,null,DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_USER_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     db.execSQL(DROP_USER_TABLE);
    onCreate(db);
}

public void addUser(User user){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_USER_MOBILE,user.getMobile());
    values.put(COLUMN_USER_EMAIL,user.getEmail());
    values.put(COLUMN_USER_MOTHERNAME,user.getMothername());
    values.put(COLUMN_USER_FATHERNAME,user.getFathername());
    values.put(COLUMN_USER_PASSWORD,user.getPass());
    values.put(COLUMN_USER_CONFIRM_PASSWORD,user.getConpass());
    db.insert(TABLE_USER,null,values);
    db.close();
}
 public boolean checkUser(String mobile, String pass ){

    String[] column = {COLUMN_USER_ID};
    SQLiteDatabase db= this.getReadableDatabase();
    String selection = COLUMN_USER_MOBILE+ " = ? " + " AND " + COLUMN_USER_PASSWORD + " = ? ";
    String[] selectionArgs = {mobile, pass};

    int cursorCount;
    try (Cursor cursor = db.query(TABLE_USER, column, selection, selectionArgs, null, null, null)) {
        cursorCount = cursor.getCount();
    }
    db.close();
    if(cursorCount > 0){
        return true;
    }

    return false;
}

Can anybody provide the necessary codes for it and explain it also .

Thank you

Body:
When You Login In LoginActivity Just Set SharedPreference

   public static final String MyPREFERENCES = "MyPrefs" ;
   public static final String Name = "nameKey";

In OnCreate()

SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();

And In MainActivity

  SharedPreferences sharedpreferences = getSharedPreferences(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = sharedpreferences.edit();
  editor.clear();
  editor.commit();


问:
Inject Javascript code into a web page
I'd like to download web page as html file. Before I save the web page source code in html file, I'd like to edit some of the page content first. I assume I can edit the content using Javascript. Unfortunately I have little experience with Javascript. I guess I have to inject my script into the web page so that the browser can execute them together. How should I write my script? Should I write a standalone script and pass the page url to my script so that they can be executed at the same time? Or there are other ways to inject my script?

EDIT: To make my problem clear, see this post and this post

答:
You can use a browser extension like Requestly to Inject custom Javascript/CSS on web pages.

This is how you can do it.

Download Requestly and Open Rules Page

Create New Rule and Select Insert Custom Script/CSS Rule Type

Enter your domain (or Page URL Pattern) and define your Script

Screenshot - Insert Script Rule

If you are looking for a Cross-Browser solution then you can use Requestly Desktop App and Configure your rule similarly.

In your particular case, you can choose an option like to run the script after page load so that all DOM Elements are present on the page before you modify/annotate them.

Disclaimer - I built Requestly

ContentLicense: CC BY-SA 3.0

Title: Inject Javascript code into a web page


问:
redirect() function not working for external URL in CodeIgniter
I want to redirect to www.yahoo.com from my codeIgniter application. I write code like this :
redirect("http://www.yahoo.com");

It is working fine in my local computer (Windows vista / WAMP) but when I upload to linux server it just show blank screen and not redirect.

答:
Blank screen normally means a fatal error somewhere. Check your logs!

And check your headers too. Curl it or use a HTTP Client to see what is being returned.

Debugging helps with these things. We are just random people on the internet without access to your computer, so without more information (hell you didnt even mention which version of CI you are using) we are all just taking guesses.


问:
Working on an auto clicker with python and I can't open the file
Every time I open the file through file explorer it immediately closes. I'm working on it through VS code and it runs fine through there but when I double click the file (.py) it opens the closes. I've tried making it into an exe (to give to my friend) through pyinstaller and without a -w it still closes and with a -w it says "Fatal error detected, Failed to execute script AutoClicker". I tried -w to see if the program would stay open but I assume that it closes because there is nothing to show.</p>
```<code>import mouse
import keyboard

while True:
    if keyboard.is_pressed(','):
        mouse.click('left')

    if keyboard.is_pressed('.'):
        break
</code>```

答:
Try using the pyautogui (and keyboard) module, as shown below:

```<code>from keyboard import is_pressed as isp
from pyautogui import click
from time import sleep

def clicky(click_key='.', stop_key='F10'):
    while not isp(stop_key):  # Execute till the stop key is pressed
        if isp(click_key):    # If click key is pressed,
            # Click the left button two times with a 0.2 second delay between clicks
            click(button='left', clicks=2, interval=0.2)
            sleep(0.5)   # Wait .5 seconds before checking again

clicky()  # Run the function
</code>```

The above code works perfectly on my Windows PC. If it does not work for you, try using the pydirectinput module, it's an updated version of pyautogui (With almost the same functions - check the link). Quoting from the PyPI page:

PyAutoGUI uses Virtual Key Codes (VKs) and the deprecated mouse_event() and keybd_event() win32 functions. You may find that PyAutoGUI does not work in some applications, particularly in video games and other software that rely on DirectX. If you find yourself in that situation, give this library a try!

Body:
Every time I open the file through file explorer it immediately closes. I'm working on it through VS code and it runs fine through there but when I double click the file (.py) it opens the closes. I've tried making it into an exe (to give to my friend) through pyinstaller and without a -w it still closes and with a -w it says "Fatal error detected, Failed to execute script AutoClicker". I tried -w to see if the program would stay open but I assume that it closes because there is nothing to show.

import mouse
import keyboard

while True:
    if keyboard.is_pressed(','):
        mouse.click('left')

    if keyboard.is_pressed('.'):
        break

Body:
Try using the pyautogui (and keyboard) module, as shown below:

from keyboard import is_pressed as isp
from pyautogui import click
from time import sleep

def clicky(click_key='.', stop_key='F10'):
    while not isp(stop_key):  # Execute till the stop key is pressed
        if isp(click_key):    # If click key is pressed,
            # Click the left button two times with a 0.2 second delay between clicks
            click(button='left', clicks=2, interval=0.2)
            sleep(0.5)   # Wait .5 seconds before checking again

clicky()  # Run the function

The above code works perfectly on my Windows PC. If it does not work for you, try using the pydirectinput module, it's an updated version of pyautogui (With almost the same functions - check the link). Quoting from the PyPI page:

PyAutoGUI uses Virtual Key Codes (VKs) and the deprecated mouse_event() and keybd_event() win32 functions. You may find that PyAutoGUI does not work in some applications, particularly in video games and other software that rely on DirectX. If you find yourself in that situation, give this library a try!


问:
Null check operator used on a null value in WebView flutter
please a error when I try to reload my webview from a button : E/flutter (18150): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Null check operator used on a null value

```<code>RaisedButton(
                        padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 30),
                        onPressed: () async {
                          controller.reload();
                        },
</code>```

this is my WebView

```<code> WebView(
                  initialUrl: "https://wikoget.com",
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (controller){
                   this.controller=controller;
                  },
                  onPageFinished: (String url) {
                    controller
                        .evaluateJavascript("javascript:(function() { " +
                        "var head = document.getElementsByClassName('main-header-bar-wrap')[0];" +
                        "head.parentNode.style.cssText = ' position: sticky;position: -webkit-sticky; top : 0 ';" +
                        "var footer = document.getElementsByTagName('footer')[0];" +
                        "footer.parentNode.removeChild(footer);" +
                        "})()")
                        .then((value) => debugPrint('Page finished loading Javascript'));
                    },
                  onWebResourceError: (error) => setState(() {
                    controller.loadUrl("about:blank");
                    isError = true;
                  }),
                  gestureNavigationEnabled: true,
                ),
</code>```

答:
enter code hereUse the fallback operator to set a default value for null values before using the variable.

```<code>String? str; //nullable value
str ??= "Fallback Value";
print(str); //Output: Fallback Value
</code>```

Here, "str" is null, and we set the fallback operator with fallback value in case of "str" is null.

Body:
please a error when I try to reload my webview from a button : E/flutter (18150): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Null check operator used on a null value

RaisedButton(
                        padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 30),
                        onPressed: () async {
                          controller.reload();
                        },

this is my WebView

 WebView(
                  initialUrl: "https://wikoget.com",
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (controller){
                   this.controller=controller;
                  },
                  onPageFinished: (String url) {
                    controller
                        .evaluateJavascript("javascript:(function() { " +
                        "var head = document.getElementsByClassName('main-header-bar-wrap')[0];" +
                        "head.parentNode.style.cssText = ' position: sticky;position: -webkit-sticky; top : 0 ';" +
                        "var footer = document.getElementsByTagName('footer')[0];" +
                        "footer.parentNode.removeChild(footer);" +
                        "})()")
                        .then((value) => debugPrint('Page finished loading Javascript'));
                    },
                  onWebResourceError: (error) => setState(() {
                    controller.loadUrl("about:blank");
                    isError = true;
                  }),
                  gestureNavigationEnabled: true,
                ),

Body:
enter code hereUse the fallback operator to set a default value for null values before using the variable.

String? str; //nullable value
str ??= "Fallback Value";
print(str); //Output: Fallback Value

Here, "str" is null, and we set the fallback operator with fallback value in case of "str" is null.


问:
How to change Odoo blog url?
I'm developing our corporate website with Odoo (v14) and for the News page, I use default website_blog app/module. I'm able to list the blog posts as news on the page/section that I want. The only thing that I couldn't change is the url.

So, by default, when you create a new post (+ New --> Blog post) it automatically creates the url of the post as:

```<code>/blog/our-blog-1/blog-title
</code>```

blog-title is, obviously, the title that you enter for the post.

our-blog-1 is the default blog and is also editable. Configuration --> Blogs (you can either edit the current ones or create a new one.)

The only thing that I couldn't figure it out is to change /blog/. I want to set this path as /news/ by default. So, the result would be like this:

```<code>/news/our-blog-1/blog-title
</code>```

I would greatly appreciate if you could help me to solve this.

答:
The /blog path come from the defined path at file website_blog/controllers/main.py under class WebsiteBlog(http.Controller):. You can do the following to change /blog to /news:

Create your own module inherited from website_blog module.

Define WebsiteBlog class inherited from existing WebsiteBlog.

Redefine def blog with your own route like the following:

```<code>from odoo.addons.website_blog.controllers.main import WebsiteBlog

class WebsiteBlog(WebsiteBlog):

    @http.route([
        '/news',
        '/news/page/<int:page>',
        '/news/tag/<string:tag>',
        '/news/tag/<string:tag>/page/<int:page>',
        '''/news/<model("blog.blog"):blog>''',
        '''/news/<model("blog.blog"):blog>/page/<int:page>''',
        '''/news/<model("blog.blog"):blog>/tag/<string:tag>''',
        '''/news/<model("blog.blog"):blog>/tag/<string:tag>/page/<int:page>''',
    ], type='http', auth="public", website=True, sitemap=True)
    def news(self, blog=None, tag=None, page=1, search=None, **opt):
        Blog = request.env['blog.blog']
        if blog and not blog.can_access_from_current_website():
            raise werkzeug.exceptions.NotFound()

        blogs = Blog.search(request.website.website_domain(), order="create_date asc, id asc")

        if not blog and len(blogs) == 1:
            return werkzeug.utils.redirect('/news/%s' % slug(blogs[0]), code=302)

        date_begin, date_end, state = opt.get('date_begin'), opt.get('date_end'), opt.get('state')

        if tag and request.httprequest.method == 'GET':
            # redirect get tag-1,tag-2 -> get tag-1
            tags = tag.split(',')
            if len(tags) > 1:
                url = QueryURL('' if blog else '/news', ['blog', 'tag'], blog=blog, tag=tags[0], date_begin=date_begin, date_end=date_end, search=search)()
                return request.redirect(url, code=302)

        values = self._prepare_blog_values(blogs=blogs, blog=blog, date_begin=date_begin, date_end=date_end, tags=tag, state=state, page=page, search=search)

        # in case of a redirection need by `_prepare_blog_values` we follow it
        if isinstance(values, werkzeug.wrappers.Response):
            return values

        if blog:
            values['main_object'] = blog
            values['edit_in_backend'] = True
            values['blog_url'] = QueryURL('', ['blog', 'tag'], blog=blog, tag=tag, date_begin=date_begin, date_end=date_end, search=search)
        else:
            values['blog_url'] = QueryURL('/news', ['tag'], date_begin=date_begin, date_end=date_end, search=search)

        return request.render("website_blog.blog_post_short", values)
</code>```

Title: How to change Odoo blog url?

Body:
I'm developing our corporate website with Odoo (v14) and for the News page, I use default website_blog app/module. I'm able to list the blog posts as news on the page/section that I want. The only thing that I couldn't change is the url.

So, by default, when you create a new post (+ New --> Blog post) it automatically creates the url of the post as:

/blog/our-blog-1/blog-title

blog-title is, obviously, the title that you enter for the post.

our-blog-1 is the default blog and is also editable. Configuration --> Blogs (you can either edit the current ones or create a new one.)

The only thing that I couldn't figure it out is to change /blog/. I want to set this path as /news/ by default. So, the result would be like this:

/news/our-blog-1/blog-title

I would greatly appreciate if you could help me to solve this.

Body:
The /blog path come from the defined path at file website_blog/controllers/main.py under class WebsiteBlog(http.Controller):. You can do the following to change /blog to /news:

Create your own module inherited from website_blog module.

Define WebsiteBlog class inherited from existing WebsiteBlog.

Redefine def blog with your own route like the following:

from odoo.addons.website_blog.controllers.main import WebsiteBlog

class WebsiteBlog(WebsiteBlog):

    @http.route([
        '/news',
        '/news/page/<int:page>',
        '/news/tag/<string:tag>',
        '/news/tag/<string:tag>/page/<int:page>',
        '''/news/<model("blog.blog"):blog>''',
        '''/news/<model("blog.blog"):blog>/page/<int:page>''',
        '''/news/<model("blog.blog"):blog>/tag/<string:tag>''',
        '''/news/<model("blog.blog"):blog>/tag/<string:tag>/page/<int:page>''',
    ], type='http', auth="public", website=True, sitemap=True)
    def news(self, blog=None, tag=None, page=1, search=None, **opt):
        Blog = request.env['blog.blog']
        if blog and not blog.can_access_from_current_website():
            raise werkzeug.exceptions.NotFound()

        blogs = Blog.search(request.website.website_domain(), order="create_date asc, id asc")

        if not blog and len(blogs) == 1:
            return werkzeug.utils.redirect('/news/%s' % slug(blogs[0]), code=302)

        date_begin, date_end, state = opt.get('date_begin'), opt.get('date_end'), opt.get('state')

        if tag and request.httprequest.method == 'GET':
            # redirect get tag-1,tag-2 -> get tag-1
            tags = tag.split(',')
            if len(tags) > 1:
                url = QueryURL('' if blog else '/news', ['blog', 'tag'], blog=blog, tag=tags[0], date_begin=date_begin, date_end=date_end, search=search)()
                return request.redirect(url, code=302)

        values = self._prepare_blog_values(blogs=blogs, blog=blog, date_begin=date_begin, date_end=date_end, tags=tag, state=state, page=page, search=search)

        # in case of a redirection need by `_prepare_blog_values` we follow it
        if isinstance(values, werkzeug.wrappers.Response):
            return values

        if blog:
            values['main_object'] = blog
            values['edit_in_backend'] = True
            values['blog_url'] = QueryURL('', ['blog', 'tag'], blog=blog, tag=tag, date_begin=date_begin, date_end=date_end, search=search)
        else:
            values['blog_url'] = QueryURL('/news', ['tag'], date_begin=date_begin, date_end=date_end, search=search)

        return request.render("website_blog.blog_post_short", values)


问:
How do I clear the capture window in Wireshark?
Is there a way to clear the capture window in Wireshark without restarting the capture or re-applying the filter? It's difficult to tell one set of traffic from another without looking very closely at the timestamp.</p>

答:
There seems to be no way to clear the window. Just hit the refresh button multiple times fast and hit STOP in the end. It will then give a warning: "No packets captured". That's all. After this you can hit the start capture button to record your packets of concern.

If it gives a pop-up asking to save the capture on hitting refresh every-time, just disable that functionality for time being. Uncheck the "Confirm unsaved capture files" field under Preferences.


问:
Jquery submits form but does not fade my div
The title almost says it all. I have a jquery code i've written, im not good at it but this is what i achieved:

```<code>$("#myForm").submit(function(){

            //alert($(this).serialize());

            $.post("submit.php", $(this).serialize(), function(data){
                if(data == success) {

                $("#add_vote").fadeOut("fast");
                $("#verification_sent").fadeIn("fast");
                $("#wrong").fadeOut("fast");

                } else {

                $("#wrong").fadeIn("fast");

                }
            });

            return false;
        });
</code>```

The form gets submitted well but the fadeIn and fadeOut's I have does not work. Do anyone know why?

答:
Verify what submit.php returns, and what is in data.

```<code>if(data == success) {
</code>```

This looks suspicious, did you meant if (data == "success") { ? (success is a variable, probably undefined; "success" is a string.)

Body:
The title almost says it all. I have a jquery code i've written, im not good at it but this is what i achieved:

$("#myForm").submit(function(){

            //alert($(this).serialize());

            $.post("submit.php", $(this).serialize(), function(data){
                if(data == success) {

                $("#add_vote").fadeOut("fast");
                $("#verification_sent").fadeIn("fast");
                $("#wrong").fadeOut("fast");

                } else {

                $("#wrong").fadeIn("fast");

                }
            });

            return false;
        });

The form gets submitted well but the fadeIn and fadeOut's I have does not work. Do anyone know why?

Body:
Verify what submit.php returns, and what is in data.

if(data == success) {

This looks suspicious, did you meant if (data == "success") { ? (success is a variable, probably undefined; "success" is a string.)


问:
Python: AWS Lambda to MySQL error catching/handling
I have two Lambda functions written in Python:

Lambda function 1: Gets 'new' data from an API, gets 'old' data from an S3 bucket (if exists), compares the new to the old and creates 3 different lists of dictionaries: inserts, updates, and deletes. Each list is passed to the next lambda function in batches (~6MB) via Lambda invocation using RequestResponse. The full datasets can vary in size from millions of records to 1 or 2.

Lambda function 2: Handles each type of data (insert, update, delete) separately - specific things happen for each type, but eventually each batch is written to MySQL using pymysql executemany.

I can't figure out the best way to handle errors. For example, let's say one of the batches being written contains a single record that has a NULL value for a field that is not allowed to be NULL in the database. That entire batch fails and I have no way of figuring out what was written to the database and what wasn't for that batch. Ideally, a notification would be triggered and the rouge record would be written somewhere where it could be human reviewed - all other records would be successfully written

Ideally, I could use something like the Bisect Batch on Function Failure available in Kinesis Firehose. It will recursively split failed batches into smaller batches and retry them until it has isolated the problematic records. These will then be sent to DLQ if one is configured. However, I don't think Kenesis Firehose will work for me because it doesn't write to RDS and therefore doesn't know which records fail.

This person https://stackoverflow.com/a/58384445/6669829 suggested using execute if executemany fails. Not sure if that will work for the larger batches. But perhaps if I stream the data from S3 instead of invoking via RequestResponse this could work?

This article (AWS Lambda batching) talks about going from Lambda to SQS to Lambda to RDS, but I'm not sure how specifically you can handle errors in that situation. Do you have to send one record at a time?

This blog uses something similar, but I'm still not sure how to adapt this for my use case or if this is even the best solution.

Looking for help in any form I can get; ideas, blog posts, tutorials, videos, etc.

Thank you!

答:
I do have a few suggestions focused on organization, debugging, and resiliency - please keep in mind assumptions are being made about your architecture

Organization

You currently have multiple dependent lambda's that are processing data. When you have a processing flow like this, the complexity of what you're trying to process dictates if you need to utilize an orchestration tool.

I would suggest orchestrating your lambda's via AWS Step Functions

Debugging

At the application level - log anything that isn't PII

Now that you're using an orchestration tool, utilize the error handling of Step Functions along with any business logic in the application to error appropriately if conditions for the next step aren't met

Resiliency

Life happens, things break, incorrect code get's pushed

Design your orchestration to put the failing event(s) your lambdas receive into a processing queue (AWS SQS, Kafka, etc..)- you can reprocess your events or if the events are at fault, DLQ them.

Here's a nice article on the use of orchestration with a design use case - give it a read


问:
How to implement a constrained linear fit in Python?
I'm trying to fit a linear model to a set of data, with the constraint that all the residuals (model - data) are positive - in other words, the model should be the "best overestimate".  Without this constraint, linear models can be easily found with numpy's polyfit as shown below.

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

x = [-4.12179107e-01, -1.40664082e-01, -5.52301563e-06,  1.82898473e-01]
y = [-4.14846251, -3.31607886, -3.57827245, -5.09914559]

plt.scatter(x,y)
coeff = np.polyfit(x,y,1)
plt.plot(x,np.polyval(coeff,x),c='r',label='numpy-polyval')
plt.plot(x,np.polyval([-2,-3.6],x),c='g',label='desired-fit') #a rough guess of the desired result
plt.legend()
</code>```

example1

Is there an efficient way to implement a linear fit with this type of constraint?

答:
Yes, the best fit is a line through the top two points.  I do an argsort to find the top Ys, compute the slope and y-intercept, and off we go:

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

x = [-4.12179107e-01, -1.40664082e-01, -5.52301563e-06,  1.82898473e-01]
y = [-4.14846251, -3.31607886, -3.57827245, -5.09914559]

plt.scatter(x,y)
coeff = np.polyfit(x,y,1)
model1 = np.polyval(coeff,x)
model1 += (y-model1).max()
print(model1)
print(sum((y-model1)**2))

z = np.argsort(y)
pt0 = (x[z[-1]],y[z[-1]])
pt1 = (x[z[-2]],y[z[-2]])
m = (pt1[1]-pt0[1])/(pt1[0]-pt0[0])
b = pt0[1]-m*pt0[0]

model2 = np.polyval([m,b],x)
print(model2)
print(sum((y-model2)**2))

plt.plot(x,model1,c='r',label='numpy-polyval')
plt.plot(x,model2,c='g',label='generated')
plt.legend()
plt.show()
</code>```

Output:

Body:
I'm trying to fit a linear model to a set of data, with the constraint that all the residuals (model - data) are positive - in other words, the model should be the "best overestimate".  Without this constraint, linear models can be easily found with numpy's polyfit as shown below.

import numpy as np
import matplotlib.pyplot as plt

x = [-4.12179107e-01, -1.40664082e-01, -5.52301563e-06,  1.82898473e-01]
y = [-4.14846251, -3.31607886, -3.57827245, -5.09914559]

plt.scatter(x,y)
coeff = np.polyfit(x,y,1)
plt.plot(x,np.polyval(coeff,x),c='r',label='numpy-polyval')
plt.plot(x,np.polyval([-2,-3.6],x),c='g',label='desired-fit') #a rough guess of the desired result
plt.legend()

example1

Is there an efficient way to implement a linear fit with this type of constraint?

Body:
Yes, the best fit is a line through the top two points.  I do an argsort to find the top Ys, compute the slope and y-intercept, and off we go:

import numpy as np
import matplotlib.pyplot as plt

x = [-4.12179107e-01, -1.40664082e-01, -5.52301563e-06,  1.82898473e-01]
y = [-4.14846251, -3.31607886, -3.57827245, -5.09914559]

plt.scatter(x,y)
coeff = np.polyfit(x,y,1)
model1 = np.polyval(coeff,x)
model1 += (y-model1).max()
print(model1)
print(sum((y-model1)**2))

z = np.argsort(y)
pt0 = (x[z[-1]],y[z[-1]])
pt1 = (x[z[-2]],y[z[-2]])
m = (pt1[1]-pt0[1])/(pt1[0]-pt0[0])
b = pt0[1]-m*pt0[0]

model2 = np.polyval([m,b],x)
print(model2)
print(sum((y-model2)**2))

plt.plot(x,model1,c='r',label='numpy-polyval')
plt.plot(x,model2,c='g',label='generated')
plt.legend()
plt.show()

Output:


问:
im getting this error on from that The tag <from> is unrecognized in this browser
ERORR=>{
Warning: The tag  is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
}

CODE=>{
}

```<code>        <input type="text" name="lastName" onChange={handleValues} placeholder="Last Name" value={Inputdata.lastName} />

        <input type="email" name="email" onChange={handleValues} placeholder="Email" value={Inputdata.email} />

        <textarea value={Inputdata.textarea} onChange={handleValues} name="textarea" placeholder="Massage...." />
</code>```

{/*

```<code>        <input type="radio" name="isAllow" checked={Inputdata.isAllow == "Allowed"}  onChange={handleValues} value="Allowed" />Allow

        <input type="radio" name="isAllow" checked={Inputdata.isAllow == "Dont Allow"} value="Dont Allow" onChange={handleValues} />Dont Allow */}

            <select value={Inputdata.cityName} onChange={handleValues} name="cityName">
            <option value="">---choose city</option>
            <option value="hyderbad">hyderbad</option>
            <option value="karachi">karachi</option>
            <option value="islamabad">islamabad</option>
            <option value="lahore">lahore</option>
            <option value="mirpur">mirpur</option>
        </select>
        </from>
</code>```

答: Maybe the tag you mean is <form> not <from>

Body:
ERORR=>{
Warning: The tag  is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
}

CODE=>{
}

        <input type="text" name="lastName" onChange={handleValues} placeholder="Last Name" value={Inputdata.lastName} />

        <input type="email" name="email" onChange={handleValues} placeholder="Email" value={Inputdata.email} />

        <textarea value={Inputdata.textarea} onChange={handleValues} name="textarea" placeholder="Massage...." />

{/*

        <input type="radio" name="isAllow" checked={Inputdata.isAllow == "Allowed"}  onChange={handleValues} value="Allowed" />Allow

        <input type="radio" name="isAllow" checked={Inputdata.isAllow == "Dont Allow"} value="Dont Allow" onChange={handleValues} />Dont Allow */}

            <select value={Inputdata.cityName} onChange={handleValues} name="cityName">
            <option value="">---choose city</option>
            <option value="hyderbad">hyderbad</option>
            <option value="karachi">karachi</option>
            <option value="islamabad">islamabad</option>
            <option value="lahore">lahore</option>
            <option value="mirpur">mirpur</option>
        </select>
        </from>


问:
JWT (JSON Web token) front end webpack error
```<code>import React, { useEffect, useState } from 'react'

import jwt from 'jsonwebtoken'

import { useNavigate } from 'react-router-dom'
import Navbar from './Shared/navbar'

export default function Home() {

const navigate = useNavigate();
const [user, setUser ] = useState('')

async function populateUser() {

     const req = await fetch('http://localhost:5000/users', {
        headers: {
            'x-access-token': localStorage.getItem('token'),
        },
    })

    const data = await req.json()
    if (data.status === 'ok') {
        console.log(data)
    } else {
        alert(data.error)
    }
}

useEffect(() => {

    const token = localStorage.getItem('token')
    if (token) {
        const user = jwt.decode(token)
        if (!user) {
            localStorage.removeItem('token')
            navigate('/login')
        }
    } else {
        populateUser()
    }
}, [])
return (
    <>
    <Navbar/>
    </>
)}
</code>```

I am trying to get user data in the front end by using jwt to decode the jwt token, however this breaks my app and I get this error

I read online that this is a recent webpack issue (v5) is there a way to fix this? I am also not sure what the error message is asking me to do. To clarify without the jwt method I do get the token back and the login is successful.

答:
Install jwt-decode

```<code>npm i jwt-decode

import jwtDecode from 'jwt-decode'
</code>```

Then

```<code>const decoded = jwtDecode(token)
console.log(decoded)
</code>```

Body:
import React, { useEffect, useState } from 'react'

import jwt from 'jsonwebtoken'

import { useNavigate } from 'react-router-dom'
import Navbar from './Shared/navbar'

export default function Home() {

const navigate = useNavigate();
const [user, setUser ] = useState('')

async function populateUser() {

     const req = await fetch('http://localhost:5000/users', {
        headers: {
            'x-access-token': localStorage.getItem('token'),
        },
    })

    const data = await req.json()
    if (data.status === 'ok') {
        console.log(data)
    } else {
        alert(data.error)
    }
}

useEffect(() => {

    const token = localStorage.getItem('token')
    if (token) {
        const user = jwt.decode(token)
        if (!user) {
            localStorage.removeItem('token')
            navigate('/login')
        }
    } else {
        populateUser()
    }
}, [])
return (
    <>
    <Navbar/>
    </>
)}

I am trying to get user data in the front end by using jwt to decode the jwt token, however this breaks my app and I get this error

I read online that this is a recent webpack issue (v5) is there a way to fix this? I am also not sure what the error message is asking me to do. To clarify without the jwt method I do get the token back and the login is successful.

Body:
Install jwt-decode

npm i jwt-decode

import jwtDecode from 'jwt-decode'

Then

const decoded = jwtDecode(token)
console.log(decoded)


问:
PowerShell Find Users from First/Last Name, Error not showing on special Character
I have a list of EN/FR users that have special characters in them. I am trying to get their SamAccountName but the script doesn't work correctly:

```<code>Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear();
cls
$ErrorActionPreference = "STOP"
$names = Import-CSV 'C:\temp\input.csv' -Header Givenname,Surname -Delimiter ","
$CompleteReport=@()
ForEach ($Name in $Names)
{
    $FirstFilter = $Name.Givenname
    $SecondFilter = $Name.Surname
    Write-Host $Name.Givenname, $Name.Surname
    $aduser = Get-ADUser -Filter { GivenName -like $FirstFilter -and Surname -like $SecondFilter}  | select enabled, GivenName,  Surname, samaccountname, UserPrincipalName
    $CompleteReport = $CompleteReport+$aduser
}
$CompleteReport | Export-Csv 'C:\output.csv' -NoTypeInformation
</code>```

The problem is my input list is not clear and that causes the loop keep on going without showing me the error on the item causing the issue.
How can I catch the user name that is causing this error?

答:
Might be possible that the error comes from empty strings on either GivenName or Surname from your CSV, as for sorting that problem, there is no way around fixing the CSV itself, searching AD Users by GivenName or Surname only will not bring accurate results. The following should at least handle the missing data from your CSV and point out those users that couldn't be found so you can fix your CSV.

```<code>$ErrorActionPreference = "STOP"
# -Delimiter ',' is already assumed
$names = Import-CSV 'C:\temp\input.csv' -Header Givenname, Surname

$result = forEach($name in $names) {
    $givenname = if($name.GivenName) {
        '(givenName={0})' -f $name.Givenname
    }
    $surname = if($name.Surname) {
        '(surname={0})' -f $name.Surname
    }
    $aduser = Get-ADUser -LDAPFilter "(&${surname}${givenname})"
    if(-not $aduser) {
        Write-Warning "Can't find Name: $($name.Givenname) and Surname: $($name.Surname)"
        continue
    }
    $aduser
}

$result | Select-Object Enabled, GivenName, Surname, SamAccountName, UserPrincipalName |
Export-Csv 'C:\output.csv' -NoTypeInformation
</code>```

Body:
I have a list of EN/FR users that have special characters in them. I am trying to get their SamAccountName but the script doesn't work correctly:

Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear();
cls
$ErrorActionPreference = "STOP"
$names = Import-CSV 'C:\temp\input.csv' -Header Givenname,Surname -Delimiter ","
$CompleteReport=@()
ForEach ($Name in $Names)
{
    $FirstFilter = $Name.Givenname
    $SecondFilter = $Name.Surname
    Write-Host $Name.Givenname, $Name.Surname
    $aduser = Get-ADUser -Filter { GivenName -like $FirstFilter -and Surname -like $SecondFilter}  | select enabled, GivenName,  Surname, samaccountname, UserPrincipalName
    $CompleteReport = $CompleteReport+$aduser
}
$CompleteReport | Export-Csv 'C:\output.csv' -NoTypeInformation

The problem is my input list is not clear and that causes the loop keep on going without showing me the error on the item causing the issue.
How can I catch the user name that is causing this error?

Body:
Might be possible that the error comes from empty strings on either GivenName or Surname from your CSV, as for sorting that problem, there is no way around fixing the CSV itself, searching AD Users by GivenName or Surname only will not bring accurate results. The following should at least handle the missing data from your CSV and point out those users that couldn't be found so you can fix your CSV.

$ErrorActionPreference = "STOP"
# -Delimiter ',' is already assumed
$names = Import-CSV 'C:\temp\input.csv' -Header Givenname, Surname

$result = forEach($name in $names) {
    $givenname = if($name.GivenName) {
        '(givenName={0})' -f $name.Givenname
    }
    $surname = if($name.Surname) {
        '(surname={0})' -f $name.Surname
    }
    $aduser = Get-ADUser -LDAPFilter "(&${surname}${givenname})"
    if(-not $aduser) {
        Write-Warning "Can't find Name: $($name.Givenname) and Surname: $($name.Surname)"
        continue
    }
    $aduser
}

$result | Select-Object Enabled, GivenName, Surname, SamAccountName, UserPrincipalName |
Export-Csv 'C:\output.csv' -NoTypeInformation


问:
After groupby, create a Series from the smallest values in one column corresponding to a value in another column
I have some data like this:

```<code>df = pd.DataFrame({'x':[1,2,3,1,1,2,3,3,2],
                   'y':['n', 'n', 'p', 'p', 'n', 'n', 'n', 'p', 'n'],
                   'z':[52,75,77,68,92,32,62,70,34]})
</code>```

I'd like to first group it by x, and then check if p exists in any of the rows of each group, and add another column to the original dataframe (or to the grouped one, and then somehow flatten it back out?) that has either None if there were no p's in that group, or the smallest number corresponding to p from the z column.

So here it'd be:

```<code>   x  y   z  t
0  1  n  52 68
3  1  p  68 68
4  1  n  92 68

   x  y   z  t
1  2  n  75 None
5  2  n  32 None
8  2  n  34 None

   x  y   z  t
2  3  p  77 70
6  3  n  62 70
7  3  p  70 70
</code>```

or flattened:

```<code>   x  y   z  t
0  1  n  52 68
3  1  p  68 68
4  1  n  92 68
1  2  n  75 None
5  2  n  32 None
8  2  n  34 None
2  3  p  77 70
6  3  n  62 70
7  3  p  70 70
</code>```

So first we'd do

```<code>g = df.groupby('x')
</code>```

But then I'm not sure how to proceed.
I'm just having a hard time wrapping my head around it and running into all sorts of pandas error.

答:
One option is to filter only the rows in the DataFrame where y is p. Then  use groupby min to get the minimal z value per group (of remaining rows). Then join back to the DataFrame on x. NaN will automatically be added for any missing values (groups which did not have any values equal to p).

```<code>df = df.join(
    df[df['y'].eq('p')].groupby('x')['z'].min().rename('t'),
    on='x'
)

   x  y   z     t
0  1  n  52  68.0
1  2  n  75   NaN
2  3  p  77  70.0
3  1  p  68  68.0
4  1  n  92  68.0
5  2  n  32   NaN
6  3  n  62  70.0
7  3  p  70  70.0
8  2  n  34   NaN
</code>```

*rename is used here to change the name of the column to the desired before joining back.

We can also sort by x with sort_values if needing the x values grouped together:

```<code>df = df.sort_values('x', ignore_index=True).join(
    df[df['y'].eq('p')].groupby('x')['z'].min().rename('t'),
    on='x'
)

   x  y   z     t
0  1  n  52  68.0
1  1  p  68  68.0
2  1  n  92  68.0
3  2  n  75   NaN
4  2  n  32   NaN
5  2  n  34   NaN
6  3  p  77  70.0
7  3  n  62  70.0
8  3  p  70  70.0
</code>```

Depending on the size of the DataFrame it may be more efficient to select only the z column initially with loc:

```<code>df = df.sort_values('x', ignore_index=True).join(
    df.loc[df['y'].eq('p'), 'z'].groupby(df['x']).min().rename('t'),
    on='x'
)

   x  y   z     t
0  1  n  52  68.0
1  1  p  68  68.0
2  1  n  92  68.0
3  2  n  75   NaN
4  2  n  32   NaN
5  2  n  34   NaN
6  3  p  77  70.0
7  3  n  62  70.0
8  3  p  70  70.0
</code>```

Body:
I have some data like this:

df = pd.DataFrame({'x':[1,2,3,1,1,2,3,3,2],
                   'y':['n', 'n', 'p', 'p', 'n', 'n', 'n', 'p', 'n'],
                   'z':[52,75,77,68,92,32,62,70,34]})

I'd like to first group it by x, and then check if p exists in any of the rows of each group, and add another column to the original dataframe (or to the grouped one, and then somehow flatten it back out?) that has either None if there were no p's in that group, or the smallest number corresponding to p from the z column.

So here it'd be:

   x  y   z  t
0  1  n  52 68
3  1  p  68 68
4  1  n  92 68

   x  y   z  t
1  2  n  75 None
5  2  n  32 None
8  2  n  34 None

   x  y   z  t
2  3  p  77 70
6  3  n  62 70
7  3  p  70 70

or flattened:

   x  y   z  t
0  1  n  52 68
3  1  p  68 68
4  1  n  92 68
1  2  n  75 None
5  2  n  32 None
8  2  n  34 None
2  3  p  77 70
6  3  n  62 70
7  3  p  70 70

So first we'd do

g = df.groupby('x')

But then I'm not sure how to proceed.
I'm just having a hard time wrapping my head around it and running into all sorts of pandas error.

Body:
One option is to filter only the rows in the DataFrame where y is p. Then  use groupby min to get the minimal z value per group (of remaining rows). Then join back to the DataFrame on x. NaN will automatically be added for any missing values (groups which did not have any values equal to p).

df = df.join(
    df[df['y'].eq('p')].groupby('x')['z'].min().rename('t'),
    on='x'
)

   x  y   z     t
0  1  n  52  68.0
1  2  n  75   NaN
2  3  p  77  70.0
3  1  p  68  68.0
4  1  n  92  68.0
5  2  n  32   NaN
6  3  n  62  70.0
7  3  p  70  70.0
8  2  n  34   NaN

*rename is used here to change the name of the column to the desired before joining back.

We can also sort by x with sort_values if needing the x values grouped together:

df = df.sort_values('x', ignore_index=True).join(
    df[df['y'].eq('p')].groupby('x')['z'].min().rename('t'),
    on='x'
)

   x  y   z     t
0  1  n  52  68.0
1  1  p  68  68.0
2  1  n  92  68.0
3  2  n  75   NaN
4  2  n  32   NaN
5  2  n  34   NaN
6  3  p  77  70.0
7  3  n  62  70.0
8  3  p  70  70.0

Depending on the size of the DataFrame it may be more efficient to select only the z column initially with loc:

df = df.sort_values('x', ignore_index=True).join(
    df.loc[df['y'].eq('p'), 'z'].groupby(df['x']).min().rename('t'),
    on='x'
)

   x  y   z     t
0  1  n  52  68.0
1  1  p  68  68.0
2  1  n  92  68.0
3  2  n  75   NaN
4  2  n  32   NaN
5  2  n  34   NaN
6  3  p  77  70.0
7  3  n  62  70.0
8  3  p  70  70.0


问:
Base Table or view not found SQLSTATE[42S02]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'vita_valorelondon.general_settings' doesn't exist (SQL: select active_template from general_settings limit 1)

Databse.php

```<code>  'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'vita_valorelondon'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => false,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],
</code>```

.env

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=vita_valorelondon
DB_USERNAME=root
DB_PASSWORD=
</code>```

How To Fix This ?

答:
Most of the times this error comes when we didn't give grant to specific schema.

example :

I create table 'users' in schema 'user'

so when I want to use it in another schema like 'product' I have to give grant to this schema from 'user' schema.

oracle code :

```<code>grant select , insert , update , delete on users to product

users : is a table in a 'user' schema

product : is a new schema that want to use of table 'users'
</code>```

Body:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'vita_valorelondon.general_settings' doesn't exist (SQL: select active_template from general_settings limit 1)

Databse.php

  'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'vita_valorelondon'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => false,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=vita_valorelondon
DB_USERNAME=root
DB_PASSWORD=

How To Fix This ?

Body:
Most of the times this error comes when we didn't give grant to specific schema.

example :

I create table 'users' in schema 'user'

so when I want to use it in another schema like 'product' I have to give grant to this schema from 'user' schema.

oracle code :

grant select , insert , update , delete on users to product

users : is a table in a 'user' schema

product : is a new schema that want to use of table 'users'


问:
How to generate multiple combinations from tables using SQL?
I have few combinations of records in my table but i want to generate Multiple combinations from original table.

Records in table

codeset
codevalue
column
system

test1
1
null
sys1

test2
2
col2
sys1

test3
3
col3
sys1

test3
4
col4
sys1

test3
5
col5
sys1

test4
null
col6
sys1

test5
6
col7
sys2

test5
7
col8
sys2

After applied below logic and would like to get expected output.

Group by 'codeset'

system name should be 'sys1'

'codevalue' and 'column' should be more than 1 row

'codevalue' and 'column' equal rows

Expected Output

codeset
codevalue
column
system

test1
1
null
sys1

test2
2
col2
sys1

test3
3
col3
sys1

test3
3
col4
sys1

test3
3
col5
sys1

test3
4
col3
sys1

test3
4
col4
sys1

test3
4
col5
sys1

test3
5
col3
sys1

test3
5
col4
sys1

test3
5
col5
sys1

test4
null
col6
sys1

test5
6
col7
sys2

test5
7
col8
sys2

答:
If you are doing it manually you can just use an insert statement for each row you want to add, eg:</p>
```<code>INSERT INTO table (codeset, codevalue, column, system ) VALUES ('test3', 3, 'col2', 'sys1' );
</code>```

Body:
If you are doing it manually you can just use an insert statement for each row you want to add, eg:

INSERT INTO table (codeset, codevalue, column, system ) VALUES ('test3', 3, 'col2', 'sys1' );


问:
A RenderFlex overflowed bottom flutter
when I run the project it shows A RenderFlex overflowed on the bottom

A RenderFlex overflowed by 6.7 pixels on the bottom.

答:
A quick solution would be to block the widgets inside the Scaffold to resize themselves when the keyboard opens but this way,</p>
```<code>return Scaffold(
      appBar: AppBar(
        title: Text('Expenses Tracker'),
      ),
      body: SingleChildScrollView( // wrap with a scrollable widget
        child: Column(
          children: <Widget>[
            ...... // other widgets
          ],
        ),
      ),
    );
</code>```

Title: A RenderFlex overflowed bottom flutter

Body:
A quick solution would be to block the widgets inside the Scaffold to resize themselves when the keyboard opens but this way,

return Scaffold(
      appBar: AppBar(
        title: Text('Expenses Tracker'),
      ),
      body: SingleChildScrollView( // wrap with a scrollable widget
        child: Column(
          children: <Widget>[
            ...... // other widgets
          ],
        ),
      ),
    );


问:
How to make scrapy spider crawl again if condition is not met?
In my close function, I am checking for the presence of a document scraped today, and I'd like to tell my Spider to scrape again if no such document is found. Basically, I need a robust way for the scraper to keep calling its crawl routine until a certain condition is met or MAX_RETRIES has been exhausted.

答:
To execute the spider after the spider has finished, you will need to use the reactor and CrawlerRunner class. The crawl method returns a deferred once the spider has finished scraping which you can use to add a callback in which you can do your checks. See below example where the spider will rerun until the number of retries >= 3 at which point it stops.

You will need to be careful how you do your checks because this is asynchronous code and the sequence of code execution might not be as one might expect.

import scrapy
from twisted.internet import reactor
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging

class ExampleSpider(scrapy.Spider):
    name = 'example'
    start_urls = ['https://example.com']

    def parse(self, response):
        yield {
            "url": response.url
        }

if __name__ == '__main__':
    RETRIES = 0
    configure_logging()
    runner = CrawlerRunner()
    d = runner.crawl(ExampleSpider)
    def finished():
        global RETRIES
        # do your checks in this callback and run the spider again if needed
        # in this example, we check if the number of retries is less than the required value
        # if not we stop the reactor
        if RETRIES < 3:
            RETRIES += 1
            d = runner.crawl(ExampleSpider)
            d.addBoth(lambda _: finished())

        else:
            reactor.stop() # stop the reactor if the condition is not met

    d.addBoth(lambda _: finished())
    reactor.run()
```


问:
How could I add current pc IP into security group with aws cli
I want to add current working PC's IP into a security group,

And enable all traffice for it. Every time I should do that manually with the web dashboard.

How could I do it with a shell script?

The following are the most common aws cli commands I used.

But I couldn't find how to add ip in a specific security group.

```<code>list_instances(){
    aws ec2 describe-instances --query 'Reservations[].Instances[].[Tags[?Key==`Name`].Value,InstanceId,PublicIpAddress,PrivateIpAddress]' --output text
}
start_instance(){
    aws ec2 start-instances --instance-ids $1
}
</code>```

答:
This small bash script serves the same purpose, the port number can be a positional argument in cli -

```<code>#!/bin/bash

TargetAddr='<IP>'
aws_sg_id='<sg-id>'

myip=$(curl -s ifconfig.me)

echo -e "Updating IP $myip in Security Group: $aws_sg_id"

aws --profile <profile-name> ec2 authorize-security-group-ingress --group-id $aws_sg_id  --protocol tcp --port 22 --cidr $myip/32 2>/dev/null

#Verifying the Access
/usr/bin/nc -zv -w1 $TargetAddr 22
</code>```

Body:
I want to add current working PC's IP into a security group,

And enable all traffice for it. Every time I should do that manually with the web dashboard.

How could I do it with a shell script?

The following are the most common aws cli commands I used.

But I couldn't find how to add ip in a specific security group.

list_instances(){
    aws ec2 describe-instances --query 'Reservations[].Instances[].[Tags[?Key==`Name`].Value,InstanceId,PublicIpAddress,PrivateIpAddress]' --output text
}
start_instance(){
    aws ec2 start-instances --instance-ids $1
}

Body:
This small bash script serves the same purpose, the port number can be a positional argument in cli -

#!/bin/bash

TargetAddr='<IP>'
aws_sg_id='<sg-id>'

myip=$(curl -s ifconfig.me)

echo -e "Updating IP $myip in Security Group: $aws_sg_id"

aws --profile <profile-name> ec2 authorize-security-group-ingress --group-id $aws_sg_id  --protocol tcp --port 22 --cidr $myip/32 2>/dev/null

#Verifying the Access
/usr/bin/nc -zv -w1 $TargetAddr 22


问:
log4net vs. Nlog
Anyone have experience for both?  How do they stack up against each other?

We are planning on using one of them for logging in an enterprise application.

References:

log4net

nlog

EDIT: We have no existing dependencies to either nlog or log4net.

答:
First look at the rest of your stack.

If you are using NHibernate, it utilizes Log4Net directly.
Other frameworks might have other specific loggers they need.

Other than that: both work fine.

I've settled on Log4Net myself.  It can be a pain to configure, and if it isn't configured correctly it is a pain to figure out what went wrong.  But you can make it do almost anything you would want from a logger.

If you don't have a standing issue with Log4Net, here is an article I wrote on how to get started with it:
http://elegantcode.com/2007/12/07/getting-started-with-log4net/

OwnerDisplayName: Greg Dean

ContentLicense: CC BY-SA 2.5

Title: log4net vs. Nlog

LastEditorDisplayName: Greg Dean

OwnerDisplayName: Chris Brandsma

LastEditorDisplayName: Chris Brandsma


问:
How to load a local picture in three20's Photo Browser
in three20's TTCatalog demo, PhotoTest1Controller.m .there's some code

```<code>[[[MockPhoto alloc]
initWithURL:@"http://ww4.sinaimg.cn/bmiddle/6e8f23a5jw1dk7pylzs8ij.jpg"
smallURL:@"http://ww4.sinaimg.cn/thumbnail/6e8f23a5jw1dk7pylzs8ij.jpg"
size:CGSizeMake(320, 480)] autorelease],
</code>```

can i replace these URLs with local path.
i put the pictures into app's bundle.

答:
File URLs (file://) should work just fine. For images in your app bundle you can use -[NSBundle URLForResource:withExtension:]:

```<code>NSURL *imageURL = [[NSBundle mainBundle] URLForResource:@"foo" withExtension:@"jpg"];
</code>```

On iOS < 4.0 you must combine path-based NSBundle methods with +[NSURL fileURLWithPath:]:

```<code>NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"jpg"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
</code>```

Body:
in three20's TTCatalog demo, PhotoTest1Controller.m .there's some code

[[[MockPhoto alloc]
initWithURL:@"http://ww4.sinaimg.cn/bmiddle/6e8f23a5jw1dk7pylzs8ij.jpg"
smallURL:@"http://ww4.sinaimg.cn/thumbnail/6e8f23a5jw1dk7pylzs8ij.jpg"
size:CGSizeMake(320, 480)] autorelease],

can i replace these URLs with local path.
i put the pictures into app's bundle.

Body:
File URLs (file://) should work just fine. For images in your app bundle you can use -[NSBundle URLForResource:withExtension:]:

NSURL *imageURL = [[NSBundle mainBundle] URLForResource:@"foo" withExtension:@"jpg"];

On iOS < 4.0 you must combine path-based NSBundle methods with +[NSURL fileURLWithPath:]:

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"jpg"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];


问:
Navigate to another screen - 'navigation.navigate' is not a function
I am trying to navigate from Screen1 to Screen2. Screen1 is being rendered in my Home screen. So far I have tried using this.props.navigation.navigate as well as what you see currently implemented.

I have created a snack expo here that recreates the exact error as well as posted some code below.

Thank you for any insight at all, I appreciate it more than you know.

EDIT:: this needs to be ran on IOS and I am using react-native-navigation

App.js

```<code> /*passing props to home is from my overall project, I left it in incase it impacted the answer*/
<Stack.Navigator initialRouteName="Home">
      <Stack.Screen name="HomeScreen" options={{ headerShown: false }}>
        {(props) => (
          <Home {...props}/>
        )}
      </Stack.Screen>
       <Stack.Screen
        name="Screen1"
        component={Screen1}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Screen2"
        component={Screen2}
        options={{ headerShown: false }}
      />
  </Stack.Navigator>
);
}

export default function App() {

  return (
<NavigationContainer>
  <MyTabs/>
</NavigationContainer>
);
</code>```

Screen1

```<code>export default class Screen1 extends React.Component {
  renderList = (props, navigation) => {
    return List.map((item, i) => {
      return (
        <View
        key={List.name}
          style={{
            width: windowWidth,
            height: scale(100),
            paddingLeft: scale(10)
          }}>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate('Screen2')}
            activeOpacity={0.7}>
                <Text style={{fontSize: 20}}>{item.name}</Text>
          </TouchableOpacity>
        </View>
      );
    });
  };

  render() {
  return (
      <View style={{top: scale(50)}}>

          <ScrollView style={{ height: windowHeight }}>
            <this.renderList />
          </ScrollView>

      </View>
    );
  }
}

</code>```

答:
You are not passing navigation props to Screen1. You can just pass navigation props to Screen1 like below code or it is better to make Screen1 as Initial Route instead of calling it as a component in Home screen.

Good method : Update following area in App.js like below

```<code>....
<Stack.Navigator initialRouteName="Screen1"> // made Screen1 as initial route
      <Stack.Screen
        name="Screen1"
        component={Screen1}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Screen2"
        component={Screen2}
        options={{ headerShown: false }}
      />
  </Stack.Navigator>
....
</code>```

Method 2 : If you want Home Screen as Initial Route, then update following area in Home.js like below

```<code>....
const Home = (props) => {
    return (
      <View>
        <Screen1 navigation={props.navigation}/> // navigation props passed to Screen1 component
      </View>
    );
}
....
</code>```

Body:
I am trying to navigate from Screen1 to Screen2. Screen1 is being rendered in my Home screen. So far I have tried using this.props.navigation.navigate as well as what you see currently implemented.

I have created a snack expo here that recreates the exact error as well as posted some code below.

Thank you for any insight at all, I appreciate it more than you know.

EDIT:: this needs to be ran on IOS and I am using react-native-navigation

App.js

 /*passing props to home is from my overall project, I left it in incase it impacted the answer*/
<Stack.Navigator initialRouteName="Home">
      <Stack.Screen name="HomeScreen" options={{ headerShown: false }}>
        {(props) => (
          <Home {...props}/>
        )}
      </Stack.Screen>
       <Stack.Screen
        name="Screen1"
        component={Screen1}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Screen2"
        component={Screen2}
        options={{ headerShown: false }}
      />
  </Stack.Navigator>
);
}

export default function App() {

  return (
<NavigationContainer>
  <MyTabs/>
</NavigationContainer>
);

Screen1

export default class Screen1 extends React.Component {
  renderList = (props, navigation) => {
    return List.map((item, i) => {
      return (
        <View
        key={List.name}
          style={{
            width: windowWidth,
            height: scale(100),
            paddingLeft: scale(10)
          }}>
          <TouchableOpacity
            onPress={() => this.props.navigation.navigate('Screen2')}
            activeOpacity={0.7}>
                <Text style={{fontSize: 20}}>{item.name}</Text>
          </TouchableOpacity>
        </View>
      );
    });
  };

  render() {
  return (
      <View style={{top: scale(50)}}>

          <ScrollView style={{ height: windowHeight }}>
            <this.renderList />
          </ScrollView>

      </View>
    );
  }
}

Body:
You are not passing navigation props to Screen1. You can just pass navigation props to Screen1 like below code or it is better to make Screen1 as Initial Route instead of calling it as a component in Home screen.

Good method : Update following area in App.js like below

....
<Stack.Navigator initialRouteName="Screen1"> // made Screen1 as initial route
      <Stack.Screen
        name="Screen1"
        component={Screen1}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Screen2"
        component={Screen2}
        options={{ headerShown: false }}
      />
  </Stack.Navigator>
....

Method 2 : If you want Home Screen as Initial Route, then update following area in Home.js like below

....
const Home = (props) => {
    return (
      <View>
        <Screen1 navigation={props.navigation}/> // navigation props passed to Screen1 component
      </View>
    );
}
....


问:
React Draft Wysiwyg - Using custom toolbar icons instead of standard inline toolbar images
Is there a way to replace the inline toolbar images with custom icons like ones from React Icons?

Code (Toolbar Options):

import { AiOutlineUnorderedList } from 'react-icons/ai'

export const toolbarOptions = {
  options: ['list', 'link'],
  list: {
    options: ['unordered', 'ordered'],
    unordered: {
      icon: <AiOutlineUnorderedList />, //does not work
      className: undefined,
    },
  },
  link: {
    options: ['link'],
  },
}
```

I have also tried to use  however that does not work as well...

Any ideas?

TIA

答:
You just need to provide the src or file path</p>
```<code>unordered: {
 icon: "../path-to.svg",
 className: undefined
}
</code>```

Body:
Is there a way to replace the inline toolbar images with custom icons like ones from React Icons?

Code (Toolbar Options):

import { AiOutlineUnorderedList } from 'react-icons/ai'

export const toolbarOptions = {
  options: ['list', 'link'],
  list: {
    options: ['unordered', 'ordered'],
    unordered: {
      icon: <AiOutlineUnorderedList />, //does not work
      className: undefined,
    },
  },
  link: {
    options: ['link'],
  },
}

I have also tried to use  however that does not work as well...

Any ideas?

TIA

Body:
You just need to provide the src or file path

unordered: {
 icon: "../path-to.svg",
 className: undefined
}


问:
Getting a syntax error for a SQL query with a call to function
I have a simple function declared and called into a query. I am getting an error at in my SQL query near dosagecount</p>
```<code>CREATE FUNCTION dosagecount
    (@dosage DECIMAL(2, 2),
     @frequency INT,
     @frequencyinterval INT)
RETURNS DECIMAL(2,2)
AS
BEGIN
    DECLARE @dosePerDay DECIMAL(2,2);

    SET @dosePerDay = @dosage * @frequency / @frequencyinterval;
    RETURN @dosePerDay
END;

DECLARE @dosagecount DECIMAL(2,2);

SELECT
    caseNumber, patientAge, gender,
    @dosagecount(dosage, frequency, frequencyinterval)
AS dosePerDay
FROM
    patientView;
</code>```

答:
Thank you for the valuable feedback.

RDBMS I'm using is SQL Server.

I finally resolved the error by making changes to the function

```<code>CREATE FUNCTION dosagecount
    (@dosage DECIMAL(9, 2),
     @frequency INT,
     @frequencyinterval INT)
RETURNS DECIMAL(9, 2)
AS
BEGIN
    DECLARE @dosePerDay DECIMAL(2, 2);

    SET @dosePerDay = @dosage * @frequency / @frequencyinterval;
    RETURN @dosePerDay
END;

DECLARE @dosagecount DECIMAL(9,2);

SELECT
    caseNumber, patientAge, gender,
    [dbo].dosagecount(dosage, frequency, frequencyinterval) AS dosePerDay
FROM
    patientView;
</code>```

Please do note the usage of [dbo]. to call the function which resolved the syntax error.

I also got an arithmetic error which was resolved by increasing the size of the decimal to 9,2

Body:
I have a simple function declared and called into a query. I am getting an error at in my SQL query near dosagecount

CREATE FUNCTION dosagecount
    (@dosage DECIMAL(2, 2),
     @frequency INT,
     @frequencyinterval INT)
RETURNS DECIMAL(2,2)
AS
BEGIN
    DECLARE @dosePerDay DECIMAL(2,2);

    SET @dosePerDay = @dosage * @frequency / @frequencyinterval;
    RETURN @dosePerDay
END;

DECLARE @dosagecount DECIMAL(2,2);

SELECT
    caseNumber, patientAge, gender,
    @dosagecount(dosage, frequency, frequencyinterval)
AS dosePerDay
FROM
    patientView;

Body:
Thank you for the valuable feedback.

RDBMS I'm using is SQL Server.

I finally resolved the error by making changes to the function

CREATE FUNCTION dosagecount
    (@dosage DECIMAL(9, 2),
     @frequency INT,
     @frequencyinterval INT)
RETURNS DECIMAL(9, 2)
AS
BEGIN
    DECLARE @dosePerDay DECIMAL(2, 2);

    SET @dosePerDay = @dosage * @frequency / @frequencyinterval;
    RETURN @dosePerDay
END;

DECLARE @dosagecount DECIMAL(9,2);

SELECT
    caseNumber, patientAge, gender,
    [dbo].dosagecount(dosage, frequency, frequencyinterval) AS dosePerDay
FROM
    patientView;

Please do note the usage of [dbo]. to call the function which resolved the syntax error.

I also got an arithmetic error which was resolved by increasing the size of the decimal to 9,2


问:
MissingPluginException(No implementation found for method vision#startImageLabelDetector on channel google_ml_kit)
I was trying a demo code on the google_ml_kit plugin and ran into this error-

```<code>
Error: MissingPluginException(No implementation found for method vision#startImageLabelDetector on channel google_ml_kit)
    at Object.throw_ [as throw] (http://localhost:61538/dart_sdk.js:5063:11)
at MethodChannel._invokeMethod (http://localhost:61538/packages/flutter/src/services/restoration.dart.lib.js:1555:21)
    at _invokeMethod.next (<anonymous>)
    at http://localhost:61538/dart_sdk.js:40192:33
    at _RootZone.runUnary (http://localhost:61538/dart_sdk.js:40062:59)
    at _FutureListener.thenAwait.handleValue (http://localhost:61538/dart_sdk.js:34983:29)
    at handleValueCallback (http://localhost:61538/dart_sdk.js:35551:49)
    at Function._propagateToListeners (http://localhost:61538/dart_sdk.js:35589:17)
    at _Future.new.[_completeWithValue] (http://localhost:61538/dart_sdk.js:35437:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:61538/dart_sdk.js:35458:35)
    at Object._microtaskLoop (http://localhost:61538/dart_sdk.js:40330:13)
    at _startMicrotaskLoop (http://localhost:61538/dart_sdk.js:40336:13)
    at http://localhost:61538/dart_sdk.js:35811:9

</code>```

Here's the implementation-

```<code>import 'package:google_ml_kit/google_ml_kit.dart';
import 'package:image_picker/image_picker.dart';

Future<List> runStuff() async {
  ImagePicker picker = ImagePicker();
  XFile? file = await picker.pickImage(source: ImageSource.gallery);
  String path = file!.path;
  InputImage inputImage = InputImage.fromFilePath(path);
  ImageLabeler imageLabeler = GoogleMlKit.vision.imageLabeler();
  List out = await imageLabeler.processImage(inputImage);
  return out;
}

</code>```

答: The exception appeared because the plug-in google_ml_kit is not supported for web but only iOS and android

Body:
I was trying a demo code on the google_ml_kit plugin and ran into this error-

Error: MissingPluginException(No implementation found for method vision#startImageLabelDetector on channel google_ml_kit)
    at Object.throw_ [as throw] (http://localhost:61538/dart_sdk.js:5063:11)
at MethodChannel._invokeMethod (http://localhost:61538/packages/flutter/src/services/restoration.dart.lib.js:1555:21)
    at _invokeMethod.next (<anonymous>)
    at http://localhost:61538/dart_sdk.js:40192:33
    at _RootZone.runUnary (http://localhost:61538/dart_sdk.js:40062:59)
    at _FutureListener.thenAwait.handleValue (http://localhost:61538/dart_sdk.js:34983:29)
    at handleValueCallback (http://localhost:61538/dart_sdk.js:35551:49)
    at Function._propagateToListeners (http://localhost:61538/dart_sdk.js:35589:17)
    at _Future.new.[_completeWithValue] (http://localhost:61538/dart_sdk.js:35437:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:61538/dart_sdk.js:35458:35)
    at Object._microtaskLoop (http://localhost:61538/dart_sdk.js:40330:13)
    at _startMicrotaskLoop (http://localhost:61538/dart_sdk.js:40336:13)
    at http://localhost:61538/dart_sdk.js:35811:9

Here's the implementation-

import 'package:google_ml_kit/google_ml_kit.dart';
import 'package:image_picker/image_picker.dart';

Future<List> runStuff() async {
  ImagePicker picker = ImagePicker();
  XFile? file = await picker.pickImage(source: ImageSource.gallery);
  String path = file!.path;
  InputImage inputImage = InputImage.fromFilePath(path);
  ImageLabeler imageLabeler = GoogleMlKit.vision.imageLabeler();
  List out = await imageLabeler.processImage(inputImage);
  return out;
}


问:
Is there a global "onRequestComplete" event when using ASP.Net Update Panels?
I have a master page with a public ShowWaitingDialog property. When set to true, I simply show a modal "Please wait..." overlay when the form is submitted. This is done by registering a client-side function called ShowWaitingDialog() using the following:

```<code>Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "ShowWaitingDialog", "ShowWaitingDialog()");
</code>```

As a side note, I also have a function the coder can use if linking to a page that may take a while to load:

```<code>public void AttachWaitingDialog(HyperLink HyperLinkControl){
if (this.ShowWaitingDialog)
    HyperLinkControl.Attributes.Add("onclick", "ShowWaitingDialog();");}
</code>```

These work just fine until an UpdatePanel is introduced onto the page. The dialog is correctly shown when a postback happens inside an update panel. However, it never goes away when the request is complete. I was hoping there was some sort of global complete event that the Microsoft ajax framework uses when making update panels requests. That way I could close my modal overflow when executed. Is there?

I haven't tried it yet, but I guess I could use the ScriptManager to always register a startup script which hides the modal overlay, but I was wondering if there was another way.

答: I'm not sure with UpdatePanels, but you might take a look at the Application_EndRequest method in Global.asax</p>

Body:
I have a master page with a public ShowWaitingDialog property. When set to true, I simply show a modal "Please wait..." overlay when the form is submitted. This is done by registering a client-side function called ShowWaitingDialog() using the following:

Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "ShowWaitingDialog", "ShowWaitingDialog()");

As a side note, I also have a function the coder can use if linking to a page that may take a while to load:

public void AttachWaitingDialog(HyperLink HyperLinkControl){
if (this.ShowWaitingDialog)
    HyperLinkControl.Attributes.Add("onclick", "ShowWaitingDialog();");}

These work just fine until an UpdatePanel is introduced onto the page. The dialog is correctly shown when a postback happens inside an update panel. However, it never goes away when the request is complete. I was hoping there was some sort of global complete event that the Microsoft ajax framework uses when making update panels requests. That way I could close my modal overflow when executed. Is there?

I haven't tried it yet, but I guess I could use the ScriptManager to always register a startup script which hides the modal overlay, but I was wondering if there was another way.


问:
Javascript: Round up to the next multiple of 5
I need a utility function that takes in an integer value (ranging from 2 to 5 digits in length) that rounds up to the next multiple of 5 instead of the nearest multiple of 5. Here is what I got:

```<code>function round5(x)
{
    return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
}
</code>```

When I run round5(32), it gives me 30, where I want 35.

When I run round5(37), it gives me 35, where I want 40.

When I run round5(132), it gives me 130, where I want 135.

When I run round5(137), it gives me 135, where I want 140.

etc...

How do I do this?

答:
New answer for old question, without if nor Math

```<code>x % 5: the remainder
5 - x % 5: the amount need to add up
(5 - x % 5) % 5: make sure it less than 5
x + (5 - x % 5) % 5: the result (x or next multiple of 5)

~~((x + N - 1) / N): equivalent to Math.ceil(x / N)
</code>```

function round5(x) {
 return x + (5 - x % 5) % 5;
}

function nearest_multiple_of(N, x) {
 return x + (N - x % N) % N;
}

function other_way_nearest_multiple_of(N, x) {
 return ~~((x + N - 1) / N) * N;
}

console.info(nearest_multiple_of(5,    0)); // 0
console.info(nearest_multiple_of(5, 2022)); // 2025
console.info(nearest_multiple_of(5, 2025)); // 2025

console.info(other_way_nearest_multiple_of(5, 2022)); // 2025
console.info(other_way_nearest_multiple_of(5, 2025)); // 2025```

Body:
I need a utility function that takes in an integer value (ranging from 2 to 5 digits in length) that rounds up to the next multiple of 5 instead of the nearest multiple of 5. Here is what I got:

function round5(x)
{
    return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
}

When I run round5(32), it gives me 30, where I want 35.

When I run round5(37), it gives me 35, where I want 40.

When I run round5(132), it gives me 130, where I want 135.

When I run round5(137), it gives me 135, where I want 140.

etc...

How do I do this?

Body:
New answer for old question, without if nor Math

x % 5: the remainder
5 - x % 5: the amount need to add up
(5 - x % 5) % 5: make sure it less than 5
x + (5 - x % 5) % 5: the result (x or next multiple of 5)

~~((x + N - 1) / N): equivalent to Math.ceil(x / N)

function round5(x) {
 return x + (5 - x % 5) % 5;
}

function nearest_multiple_of(N, x) {
 return x + (N - x % N) % N;
}

function other_way_nearest_multiple_of(N, x) {
 return ~~((x + N - 1) / N) * N;
}

console.info(nearest_multiple_of(5,    0)); // 0
console.info(nearest_multiple_of(5, 2022)); // 2025
console.info(nearest_multiple_of(5, 2025)); // 2025

console.info(other_way_nearest_multiple_of(5, 2022)); // 2025
console.info(other_way_nearest_multiple_of(5, 2025)); // 2025


问:
Binarize Picture with Core Image on iOS
I was wondering if it is possible to binarize an image (convert to black and white only) with Core Image?

I made it with OpenCV and GPUImage, but would prefer it to use Apple Core Image, if that's possible

答:
```<code>let outputImage = inputImage.applyingFilter("CIColorMonochrome",
                            parameters: [kCIInputColorKey: CIColor.white])
</code>```

In you want to play with every out of 250 CIFilters please check this app out: https://apps.apple.com/us/app/filter-magic/id1594986951

Title: Binarize Picture with Core Image on iOS

Body:
let outputImage = inputImage.applyingFilter("CIColorMonochrome",
                            parameters: [kCIInputColorKey: CIColor.white])

In you want to play with every out of 250 CIFilters please check this app out: https://apps.apple.com/us/app/filter-magic/id1594986951


问:
Simple function cannot modify a list containing just one element
I have a basic function that manipulates a tuple of two-element lists (e.g. (["a","b"],["c","d"])). I also want it to be able to handle a one-element list (e.g. (["a","b"],["c"])).

I tried two solutions which are simple but fail. It looks like the lines of code are being run non-sequentially and causing problems.

The function looks a bit like this:

```<code>def example_func(*args):
    text = ([])
    for a in args:
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)

example_func(['Hello', "gobbledy"], ['World', "gook"])
# Correct output --> [('foo:gobbledy', 'Hello'), ('foo:gook', 'World')]
example_func(['Hello', "gobbledy"], ['World', " "])
# Correct output --> [('foo:gobbledy', 'Hello'), ('foo: ', 'World')]
</code>```

However if I remove gook it will fail, so I tried to make an exception for that...

```<code>def example_func(*args):
    text = ([])
    for a in args:
        try:            # Just add a try/except condition
            text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
        except Exception:
            text = ([(f"foo: ", str(a[0])) for a in args])
    print(text)

    example_func(['Hello', "gobbledy"], ['World']) # --> Causes index error
</code>```

This fails as it runs into an index error. So instead I tried...

```<code>def example_func(*args):
    text = ([])
    for a in args:
        if len(a) == 1: # If there's just one element, add a 2nd containing whitespace
            a.append(" ")
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)
example_func(['Hello', "gobbledy"], ['World'])

# This gives an incorrect output:

# [('foo:', 'Hello'), ('foo:', 'World')] --> actual output (fails to print `gobbledy`)
# [('foo:gobbledy', 'Hello'), ('foo:', 'World')] --> desired ouput
</code>```

So when I was experimenting I tried:

```<code>def example_func(*args):
    text = ([])
    for a in args:
        print("a: ", a)
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)

example_func(['Hello', "gobbledy"], ['World', " "]) # Works
example_func(['Hello', "gobbledy"], ['World']) #FAILS, and doesn't even print the second `a`
</code>```

As the second attempt to run the for-loop fails without printing a:  ['World'] as you would expect, it looks like it's running the the comprehension and failing before the print command.

Of course the loop without the comprehension works perfectly. I'm sure it's an elementary mistake in syntax or understanding but I'm really confused.

答:
I think you are overthinking this:

```<code>def example_func(*args):
    text = []
    for a in args:
        if len(a) == 1:
            text.append( ("foo:",a[0]) )
        else:
            text.append( (f"foo:{a[1]}", a[0]) )
    print(text)

example_func(['Hello', "gobbledy"], ['World', " "]) # Works
example_func(['Hello', "gobbledy"], ['World'])
</code>```

Output:

```<code>[('foo:gobbledy', 'Hello'), ('foo: ', 'World')]
[('foo:gobbledy', 'Hello'), ('foo:', 'World')]
</code>```

Body:
I have a basic function that manipulates a tuple of two-element lists (e.g. (["a","b"],["c","d"])). I also want it to be able to handle a one-element list (e.g. (["a","b"],["c"])).

I tried two solutions which are simple but fail. It looks like the lines of code are being run non-sequentially and causing problems.

The function looks a bit like this:

def example_func(*args):
    text = ([])
    for a in args:
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)

example_func(['Hello', "gobbledy"], ['World', "gook"])
# Correct output --> [('foo:gobbledy', 'Hello'), ('foo:gook', 'World')]
example_func(['Hello', "gobbledy"], ['World', " "])
# Correct output --> [('foo:gobbledy', 'Hello'), ('foo: ', 'World')]

However if I remove gook it will fail, so I tried to make an exception for that...

def example_func(*args):
    text = ([])
    for a in args:
        try:            # Just add a try/except condition
            text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
        except Exception:
            text = ([(f"foo: ", str(a[0])) for a in args])
    print(text)

    example_func(['Hello', "gobbledy"], ['World']) # --> Causes index error

This fails as it runs into an index error. So instead I tried...

def example_func(*args):
    text = ([])
    for a in args:
        if len(a) == 1: # If there's just one element, add a 2nd containing whitespace
            a.append(" ")
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)
example_func(['Hello', "gobbledy"], ['World'])

# This gives an incorrect output:

# [('foo:', 'Hello'), ('foo:', 'World')] --> actual output (fails to print `gobbledy`)
# [('foo:gobbledy', 'Hello'), ('foo:', 'World')] --> desired ouput

So when I was experimenting I tried:

def example_func(*args):
    text = ([])
    for a in args:
        print("a: ", a)
        text = ([(f"foo:{a[1]}", str(a[0])) for a in args])
    print(text)

example_func(['Hello', "gobbledy"], ['World', " "]) # Works
example_func(['Hello', "gobbledy"], ['World']) #FAILS, and doesn't even print the second `a`

As the second attempt to run the for-loop fails without printing a:  ['World'] as you would expect, it looks like it's running the the comprehension and failing before the print command.

Of course the loop without the comprehension works perfectly. I'm sure it's an elementary mistake in syntax or understanding but I'm really confused.

Body:
I think you are overthinking this:

def example_func(*args):
    text = []
    for a in args:
        if len(a) == 1:
            text.append( ("foo:",a[0]) )
        else:
            text.append( (f"foo:{a[1]}", a[0]) )
    print(text)

example_func(['Hello', "gobbledy"], ['World', " "]) # Works
example_func(['Hello', "gobbledy"], ['World'])

Output:

[('foo:gobbledy', 'Hello'), ('foo: ', 'World')]
[('foo:gobbledy', 'Hello'), ('foo:', 'World')]