问:
I am not sure why I am getting output for this?
I was learning some string handling in C++ and was doing hit and trail on a code and surprisingly got output for the given code.

```<code>#include<bits/stdc++.h>
using namespace std;
int main(){
    char str[12]={'\67','a','v','i'};
    cout<<str;
    return 0;
}
</code>```

Surprisingly I get 7avi printed .

But if I replace '\67' with '\68'. The following error is shown on Repl.it (https://repl.it/languages/cpp)

```<code>#include<bits/stdc++.h>

using namespace std;

int main(){
    char str[12]={'\68','a','v','i'};
    cout<<str;
    return 0;
}

main.cpp:6:19: warning: multi-character character constant [-Wmultichar]
    char str[12]={'\68','a','v','i'};
                  ^
main.cpp:6:19: error: constant expression evaluates to 1592 which cannot
      be narrowed to type 'char' [-Wc++11-narrowing]
    char str[12]={'\68','a','v','i'};
                  ^~~~~
main.cpp:6:19: note: insert an explicit cast to silence this issue
    char str[12]={'\68','a','v','i'};
                  ^~~~~
                  static_cast<char>( )
main.cpp:6:19: warning: implicit conversion from 'int' to 'char' changes
      value from 1592 to 56 [-Wconstant-conversion]
    char str[12]={'\68','a','v','i'};
                 ~^~~~~
2 warnings and 1 error generated.
compiler exit status 1
</code>```

Please someone explain this behavior.

答:
I think you're trying to type in an ASCII character using either octal or hex.(octal usually begins with a 0, but hex with a 0x). Just don't put the the ASCII code in quotes, instead put the code straight into the array, like so:

```<code>char str[12] = {68, 'a', 'v', 'i'}; //decimal
char str[12] = {0x44, 'a', 'v', 'i'}; //hex
char str[12] = {0104, 'a', 'v', 'i'}; //octal
</code>```

Side Note

Please don't use <bits/stdc++.h>. It's not standardized(see here, for a more detailed explanation.) Instead include <iostream> for cout and the other requisite libraries for your other needs.

Body:
I was learning some string handling in C++ and was doing hit and trail on a code and surprisingly got output for the given code.

#include<bits/stdc++.h>
using namespace std;
int main(){
    char str[12]={'\67','a','v','i'};
    cout<<str;
    return 0;
}

Surprisingly I get 7avi printed .

But if I replace '\67' with '\68'. The following error is shown on Repl.it (https://repl.it/languages/cpp)

#include<bits/stdc++.h>

using namespace std;

int main(){
    char str[12]={'\68','a','v','i'};
    cout<<str;
    return 0;
}

main.cpp:6:19: warning: multi-character character constant [-Wmultichar]
    char str[12]={'\68','a','v','i'};
                  ^
main.cpp:6:19: error: constant expression evaluates to 1592 which cannot
      be narrowed to type 'char' [-Wc++11-narrowing]
    char str[12]={'\68','a','v','i'};
                  ^~~~~
main.cpp:6:19: note: insert an explicit cast to silence this issue
    char str[12]={'\68','a','v','i'};
                  ^~~~~
                  static_cast<char>( )
main.cpp:6:19: warning: implicit conversion from 'int' to 'char' changes
      value from 1592 to 56 [-Wconstant-conversion]
    char str[12]={'\68','a','v','i'};
                 ~^~~~~
2 warnings and 1 error generated.
compiler exit status 1

Please someone explain this behavior.

Body:
I think you're trying to type in an ASCII character using either octal or hex.(octal usually begins with a 0, but hex with a 0x). Just don't put the the ASCII code in quotes, instead put the code straight into the array, like so:

char str[12] = {68, 'a', 'v', 'i'}; //decimal
char str[12] = {0x44, 'a', 'v', 'i'}; //hex
char str[12] = {0104, 'a', 'v', 'i'}; //octal

Side Note

Please don't use <bits/stdc++.h>. It's not standardized(see here, for a more detailed explanation.) Instead include <iostream> for cout and the other requisite libraries for your other needs.


来源: stackexchange

问:
How to push to view in tabbar with some data in a variable?
I have an tabbar which includes:
    TabBar
        - HomeView -> UserProfileView -> Gallery
        - LeaderBoardView
        - SettingView
        - ........
Here, from homeview, user can go to userProfileView to select various options(camera, gallery, avatar) to change user profile in homeview.
Let's say, user choose gallery, he/she goes to gallery, choose image and the code will push back to homeview, with image. The user profile image will change, but the tab bar controllers got disappeared. It's same case with choosing avatar too.

It is not possible to push to tabbar view since, we need the image to be in homeview, because variable for image is in homeview. Can we push to tabbar view and image data in homeview?? Or can we push to homeview and keep tab bar controllers shown.

I am new to xcode/Swift. I am trying to make a quiz app as a practice.
 I have used

```<code>NavigationController.pushviewController
</code>```

Here are some code that refers to the problem.

```<code>    fileprivate func presentPhotoPickerController() {
        let myPickerController = UIImagePickerController()
        myPickerController.allowsEditing = true
        myPickerController.delegate = self
        myPickerController.sourceType = .photoLibrary
        self.present(myPickerController, animated: true)
    }

@IBAction func goToGalleryBtn(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            PHPhotoLibrary.requestAuthorization { (status) in
                switch status {
                case .authorized:
                    self.presentPhotoPickerController()
                    break
                case .notDetermined:
                    if status == PHAuthorizationStatus.authorized{
                        self.presentPhotoPickerController()
                    }
                case .restricted:
                    let alert = UIAlertController(title: "Photo Library Restricted", message: "Photo Library access is restricted and cannot be accessed.", preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "OK", style: .default)
                    alert.addAction(okAction)
                    self.present(alert, animated: true)
                case .denied:
                    let alert = UIAlertController(title: "Photo Library Denied", message: "Photo Library access was previously denied. Please update your Settings if you wish to change this.", preferredStyle: .alert)
                    let goToSettingsAction = UIAlertAction(title: "Go to Settings", style: .default){(action) in
                        DispatchQueue.main.async {
                            let url = URL(string: UIApplication.openSettingsURLString)!
                            UIApplication.shared.open(url, options: [:])
                        }
                    }
                    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
                    alert.addAction(goToSettingsAction)
                    alert.addAction(cancelAction)
                    self.present(alert, animated: true)
                }
            }
        }
    }

    @IBAction func cancelBtn(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

extension UserAvatarViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.editedImage] as? UIImage{
            imageGallery = image
        }else if let image = info[.originalImage] as? UIImage{
            imageGallery = image
        }
        dismiss(animated: true, completion: nil)

        let storyBoard: UIStoryboard = UIStoryboard(name: "HomeViewController", bundle: nil)
        let homeVC = storyBoard.instantiateViewController(withIdentifier: "HomeVC") as! HomeViewController
        homeVC.imageView = imageGallery
//        self.navigationController?.pushViewController(homeVC, animated: true)
        self.navigationController?.popViewController(animated: true)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}
</code>```

By the way, I have used different storyboards to every view controller.

答:
```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.editedImage] as? UIImage{
        imageGallery = image
    }else if let image = info[.originalImage] as? UIImage{
        imageGallery = image
    }
    dismiss(animated: true, completion: nil)

    let storyBoard:UIStoryboard = UIStoryboard(name: "TabBarViewController", bundle: nil)
    let tabBarVC = storyBoard.instantiateViewController(withIdentifier: "TabBarVC") as! UITabBarController
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = tabBarVC
    let navBar = tabBarVC.viewControllers![0] as! UINavigationController
    let homeVC = navBar.topViewController as! HomeViewController
    homeVC.imageView = imageGallery
    self.navigationController?.popViewController(animated: true)
}
</code>```

This finally worked. Thanks Hisenberg and Najeeb ur Rehman for giving me tips on using Tab bar view controller and its children.

ContentLicense: CC BY-SA 4.0

Body:
I have an tabbar which includes:
    TabBar
        - HomeView -> UserProfileView -> Gallery
        - LeaderBoardView
        - SettingView
        - ........
Here, from homeview, user can go to userProfileView to select various options(camera, gallery, avatar) to change user profile in homeview.
Let's say, user choose gallery, he/she goes to gallery, choose image and the code will push back to homeview, with image. The user profile image will change, but the tab bar controllers got disappeared. It's same case with choosing avatar too.

It is not possible to push to tabbar view since, we need the image to be in homeview, because variable for image is in homeview. Can we push to tabbar view and image data in homeview?? Or can we push to homeview and keep tab bar controllers shown.

I am new to xcode/Swift. I am trying to make a quiz app as a practice.
 I have used

NavigationController.pushviewController

Here are some code that refers to the problem.

    fileprivate func presentPhotoPickerController() {
        let myPickerController = UIImagePickerController()
        myPickerController.allowsEditing = true
        myPickerController.delegate = self
        myPickerController.sourceType = .photoLibrary
        self.present(myPickerController, animated: true)
    }

@IBAction func goToGalleryBtn(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            PHPhotoLibrary.requestAuthorization { (status) in
                switch status {
                case .authorized:
                    self.presentPhotoPickerController()
                    break
                case .notDetermined:
                    if status == PHAuthorizationStatus.authorized{
                        self.presentPhotoPickerController()
                    }
                case .restricted:
                    let alert = UIAlertController(title: "Photo Library Restricted", message: "Photo Library access is restricted and cannot be accessed.", preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "OK", style: .default)
                    alert.addAction(okAction)
                    self.present(alert, animated: true)
                case .denied:
                    let alert = UIAlertController(title: "Photo Library Denied", message: "Photo Library access was previously denied. Please update your Settings if you wish to change this.", preferredStyle: .alert)
                    let goToSettingsAction = UIAlertAction(title: "Go to Settings", style: .default){(action) in
                        DispatchQueue.main.async {
                            let url = URL(string: UIApplication.openSettingsURLString)!
                            UIApplication.shared.open(url, options: [:])
                        }
                    }
                    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
                    alert.addAction(goToSettingsAction)
                    alert.addAction(cancelAction)
                    self.present(alert, animated: true)
                }
            }
        }
    }

    @IBAction func cancelBtn(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

extension UserAvatarViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.editedImage] as? UIImage{
            imageGallery = image
        }else if let image = info[.originalImage] as? UIImage{
            imageGallery = image
        }
        dismiss(animated: true, completion: nil)

        let storyBoard: UIStoryboard = UIStoryboard(name: "HomeViewController", bundle: nil)
        let homeVC = storyBoard.instantiateViewController(withIdentifier: "HomeVC") as! HomeViewController
        homeVC.imageView = imageGallery
//        self.navigationController?.pushViewController(homeVC, animated: true)
        self.navigationController?.popViewController(animated: true)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}

By the way, I have used different storyboards to every view controller.

Body:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.editedImage] as? UIImage{
        imageGallery = image
    }else if let image = info[.originalImage] as? UIImage{
        imageGallery = image
    }
    dismiss(animated: true, completion: nil)

    let storyBoard:UIStoryboard = UIStoryboard(name: "TabBarViewController", bundle: nil)
    let tabBarVC = storyBoard.instantiateViewController(withIdentifier: "TabBarVC") as! UITabBarController
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = tabBarVC
    let navBar = tabBarVC.viewControllers![0] as! UINavigationController
    let homeVC = navBar.topViewController as! HomeViewController
    homeVC.imageView = imageGallery
    self.navigationController?.popViewController(animated: true)
}

This finally worked. Thanks Hisenberg and Najeeb ur Rehman for giving me tips on using Tab bar view controller and its children.


问:
Can I use cumulative distributed function in Gekko's intermediate variables?
I'm trying to solve a nonlinear optimization problem using Gekko where one of my intermediate variables are calculated using a cumulative distribution function of a normal distribution, i.e. 1-CDF(μ,σ, Rs-X) where Rs is another Gekko intermediate variable and μ, σ and X are Gekko parameters/Python variables.

I've also implemented this using Gekko's if3 function that returns the number 1 if Rs-X is not positive.

    n = len(df_inputs.index)    # rows
    surplus = m.Array(m.Var,(n,1))
    R_sns = m.Array(m.Var,(n,1))
    R_s = m.Array(m.Var,(n,1))
    pi_s = m.Array(m.Var,(n,1))
    for i in range (n):
        surplus[i,0].value =...
        R_sns[i,0].value = m.max3(x,surplus[i,0])
        R_s[i,0].value=m.Intermediate(0.88*R_sns[i,0])
        pi_s[i,0].value = m.if3(R_s[i,0]-x<=0,1,1-norm.cdf(R_s[i,0]-x,df_inputs['Mu'].iloc[i]*0.5,df_inputs['Sigma'].iloc[i]*0.707))
```

I'm getting a "TypeError: object of type 'int' has no len()" on that last line of code above. This error seems to be caused by the intermediate variable Rs. I tried replacing that with a fixed number and the error went away.

Traceback (most recent call last):
    File "solve_v2.py", line 59, in
      pi_s[i,0].value = m.if3(R_s[i,0]-x<=0,1,1-norm.cdf(R_s[i,0]-x,df_inputs['Mu'].iloc[i]*0.5,df_inputs['Sigma'].iloc[i]*0.707))
   ...
    File "C:\Users\Programs\Python\Python37\lib\site-packages\gekko\gk_operators.py", line 25, in len
      return len(self.value)
    File "C:\Users\Programs\Python\Python37\lib\site-packages\gekko\gk_operators.py", line 137, in len
      return len(self.value)
  TypeError: object of type 'int' has no len()

How do I get around this error?

答:
This error occurs because norm.cdf is not a Gekko function and cannot provide exact first and second derivatives to the gradient-based solver. If a function isn't in Gekko, there are few options such as: (1) request that the function is added by requesting the feature in the Gekko Github repository or (2) create an approximation of the function. One way to create an approximation of the stats.norm.cdf function is to create a cubic spline. Below is an example:

from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# create cspline of CDF
xp = np.linspace(-5,5,100)
yp = norm.cdf(xp,loc=0,scale=1)
c = GEKKO()
x = c.Var()
y = c.Var()
c.cspline(x,y,xp,yp,True)

# use cspline of CDF in optimization problem
c.Obj((y-0.75)**2)
c.solve(disp=False)

# plot results
plt.figure()
plt.plot(xp,yp,5,'b-')
plt.plot(x.value,y.value,'ro')
plt.ylim([-0.1,1.1])
plt.show()
```

<p><img src="https://i.stack.imgur.com/yKUCJ.png" alt="Cubic spline of Cumulative distribution function"></p>

<p>If the spline approximation includes two dependent variables then the <code>bspline</code> function is a better choice.</p>

<p>One other issue with your script above is the use of the Gekko <code>if3</code> function. You can leave out the <code><=</code> in your first argument. It is already implied as shown in the function help.</p>

```        Usage: y = m.if3(condition,x1,x2)
        Inputs:
           condition: GEKKO variable, parameter, or expression
           x1 and x2: GEKKO variable, parameter, or expression
        Output: GEKKO variable y = x1 when condition<0
                               y = x2 when condition>=0
```

Body:
I'm trying to solve a nonlinear optimization problem using Gekko where one of my intermediate variables are calculated using a cumulative distribution function of a normal distribution, i.e. 1-CDF(μ,σ, Rs-X) where Rs is another Gekko intermediate variable and μ, σ and X are Gekko parameters/Python variables.

I've also implemented this using Gekko's if3 function that returns the number 1 if Rs-X is not positive.

    n = len(df_inputs.index)    # rows
    surplus = m.Array(m.Var,(n,1))
    R_sns = m.Array(m.Var,(n,1))
    R_s = m.Array(m.Var,(n,1))
    pi_s = m.Array(m.Var,(n,1))
    for i in range (n):
        surplus[i,0].value =...
        R_sns[i,0].value = m.max3(x,surplus[i,0])
        R_s[i,0].value=m.Intermediate(0.88*R_sns[i,0])
        pi_s[i,0].value = m.if3(R_s[i,0]-x<=0,1,1-norm.cdf(R_s[i,0]-x,df_inputs['Mu'].iloc[i]*0.5,df_inputs['Sigma'].iloc[i]*0.707))

I'm getting a "TypeError: object of type 'int' has no len()" on that last line of code above. This error seems to be caused by the intermediate variable Rs. I tried replacing that with a fixed number and the error went away.

Traceback (most recent call last):
    File "solve_v2.py", line 59, in
      pi_s[i,0].value = m.if3(R_s[i,0]-x<=0,1,1-norm.cdf(R_s[i,0]-x,df_inputs['Mu'].iloc[i]*0.5,df_inputs['Sigma'].iloc[i]*0.707))
   ...
    File "C:\Users\Programs\Python\Python37\lib\site-packages\gekko\gk_operators.py", line 25, in len
      return len(self.value)
    File "C:\Users\Programs\Python\Python37\lib\site-packages\gekko\gk_operators.py", line 137, in len
      return len(self.value)
  TypeError: object of type 'int' has no len()

How do I get around this error?

Body:
This error occurs because norm.cdf is not a Gekko function and cannot provide exact first and second derivatives to the gradient-based solver. If a function isn't in Gekko, there are few options such as: (1) request that the function is added by requesting the feature in the Gekko Github repository or (2) create an approximation of the function. One way to create an approximation of the stats.norm.cdf function is to create a cubic spline. Below is an example:

from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# create cspline of CDF
xp = np.linspace(-5,5,100)
yp = norm.cdf(xp,loc=0,scale=1)
c = GEKKO()
x = c.Var()
y = c.Var()
c.cspline(x,y,xp,yp,True)

# use cspline of CDF in optimization problem
c.Obj((y-0.75)**2)
c.solve(disp=False)

# plot results
plt.figure()
plt.plot(xp,yp,5,'b-')
plt.plot(x.value,y.value,'ro')
plt.ylim([-0.1,1.1])
plt.show()

If the spline approximation includes two dependent variables then the bspline function is a better choice.

One other issue with your script above is the use of the Gekko if3 function. You can leave out the <= in your first argument. It is already implied as shown in the function help.

        Usage: y = m.if3(condition,x1,x2)
        Inputs:
           condition: GEKKO variable, parameter, or expression
           x1 and x2: GEKKO variable, parameter, or expression
        Output: GEKKO variable y = x1 when condition<0
                               y = x2 when condition>=0


问:
MySQL and PHP not inserting rows with spaces or special characters
I have an Android App that I program, when users search parts, my php document on my web server I have setup to add what they searched into another table to just tack how many searches are being done through the app, when a field has no spaces it adds to the table just fine, however if the field has a space or special chars in it like a dash, it dose not insert into the table. I'm at a loss how to get this to work properly and I'm hoping someone might some insight into what I'm doing wrong here. Thank you all in advanced :)

PHP Code Server Side (MySql DB)

```<code>$sql = "INSERT INTO USAGE_STATS (ITEM_NAME, FSC, NIIN, PART_NUMBER)
VALUES ('$ITEM_NAME', '$FSC', '$NIIN', $PART_NUMBER)";

if ($conn->query($sql) === TRUE) {
    $row = mysqli_insert_id($conn);
} else {
    //do nothing
}
</code>```

The colation is set to "utf8_general_ci," feilds are set to "Text," and the datebase is a MyISAM

Edit:
Just tried another part, and the full part number is "5-86510-53" but when it was inserted into the table it just came out to "-86558" in the DB

UPDATE EDIT: No this has not been answered before, I was not asking how to prevent SQL injection attacks, I was asking what I was doing wrong here.... offering advice that I should do prepared statements is the kind of advice I was looking for. I want to thank everyone for pointing me in the right direction, but marking me down for asking a question about what I was doing wrong is not what I thought this site was supposed to be about... but thank you again to those who offered meaningful assistance :)

答:
The basic mistake here is treating non-numerical data, as if it was purely numeric.

and the full part number is "5-86510-53" but when it was inserted into the table it just came out to "-86558" in the DB”

That’s because you told the database to do the calculation 5 minus 86510 minus 53. This is textual data, not numeric data, so it needs to be enclosed in quotes, when inserted into an SQL query directly.

https://dev.mysql.com/doc/refman/8.0/en/string-literals.html

(Prepared statements solve this differently.)

Body:
I have an Android App that I program, when users search parts, my php document on my web server I have setup to add what they searched into another table to just tack how many searches are being done through the app, when a field has no spaces it adds to the table just fine, however if the field has a space or special chars in it like a dash, it dose not insert into the table. I'm at a loss how to get this to work properly and I'm hoping someone might some insight into what I'm doing wrong here. Thank you all in advanced :)

PHP Code Server Side (MySql DB)

$sql = "INSERT INTO USAGE_STATS (ITEM_NAME, FSC, NIIN, PART_NUMBER)
VALUES ('$ITEM_NAME', '$FSC', '$NIIN', $PART_NUMBER)";

if ($conn->query($sql) === TRUE) {
    $row = mysqli_insert_id($conn);
} else {
    //do nothing
}

The colation is set to "utf8_general_ci," feilds are set to "Text," and the datebase is a MyISAM

Edit:
Just tried another part, and the full part number is "5-86510-53" but when it was inserted into the table it just came out to "-86558" in the DB

UPDATE EDIT: No this has not been answered before, I was not asking how to prevent SQL injection attacks, I was asking what I was doing wrong here.... offering advice that I should do prepared statements is the kind of advice I was looking for. I want to thank everyone for pointing me in the right direction, but marking me down for asking a question about what I was doing wrong is not what I thought this site was supposed to be about... but thank you again to those who offered meaningful assistance :)


问:
Overriding RouteValueDictionary in a Constraint in ASP.NET Core
I've just started using ASP.NET Core MVC and I want one route (global slug) to go to multiple controllers and actions depending on what type of page I'm serving to the user. For example, I want to use {*slug} for category and product pages.

I'm trying to override the default controller and action in a constraint.

In past versions of MVC, you could change either values["controller"] or values["action"] in a constraint and it would re-route to the appropriate controller and action.

```<code>public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        app.UseMvc(routes =>
                    {
                        routes.MapRoute(
                            name: "Category",
                            template: "{*slug}",
                            defaults: new { controller = "Page", action = "Home" },
                            constraints: new { slug = new PageConstraint() }
                            );
                    });

    }

}

public partial class PageConstraint : IRouteConstraint
{
    public virtual bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (routeDirection == RouteDirection.UrlGeneration)
        {
            return true;
        }

        var slug = values["slug"] != null ? values["slug"].ToString() : null;

        if (string.IsNullOrWhiteSpace(slug))
        {
            // Homepage
            return true;
        }

        // Get category service
        var categoryService = httpContext.RequestServices.GetRequiredService<ICategoryService>();

        var category = categoryService.GetBySlug(slug);

        if (category == null)
        {
            return false;
        }

        values["controller"] = "Category";
        values["action"] = "Listing";
        values["category"] = category;

        return true;
    }
}
</code>```

In PageConstraint, I look to see if the Category exists, and if it does, it changes the Controller to Category and the Action to Listing in the RouteValueDictionary. However, when I debug the code through, it still goes to the Controller Page and the Action Home.

Anyone know why this is happening, or whether there is a better way of doing this? I know I could have one action in a controller doing all the work that the constraint is, but I would prefer to house the code in separate controllers and actions.

答:
For your requirement, you could try to implement custom IRouter

```<code>public class RouterFromAppSettings : IRouter
{
    private readonly IRouter _defaulRouter;
    private readonly IConfiguration _config;
    public RouterFromAppSettings(IRouter defaulRouter
        , IConfiguration config)
    {
        _defaulRouter = defaulRouter;
        _config = config;
    }
    public async Task RouteAsync(RouteContext context)
    {
        var controller = _config.GetSection("Router").GetValue<string>("Controller");
        var action = _config.GetSection("Router").GetValue<string>("Action");
        context.RouteData.Values["controller"] = controller;
        context.RouteData.Values["action"] = action;
        await _defaulRouter.RouteAsync(context);
    }
    public VirtualPathData GetVirtualPath(VirtualPathContext context)
    {
        return _defaulRouter.GetVirtualPath(context);
    }
}
</code>```

And then register it in Startup.cs like

```<code>app.UseMvc(routes =>
{
    routes.Routes.Insert(0, new RouterFromAppSettings(routes.DefaultHandler,Configuration));

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});
</code>```

Body:
I've just started using ASP.NET Core MVC and I want one route (global slug) to go to multiple controllers and actions depending on what type of page I'm serving to the user. For example, I want to use {*slug} for category and product pages.

I'm trying to override the default controller and action in a constraint.

In past versions of MVC, you could change either values["controller"] or values["action"] in a constraint and it would re-route to the appropriate controller and action.

public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        app.UseMvc(routes =>
                    {
                        routes.MapRoute(
                            name: "Category",
                            template: "{*slug}",
                            defaults: new { controller = "Page", action = "Home" },
                            constraints: new { slug = new PageConstraint() }
                            );
                    });

    }

}

public partial class PageConstraint : IRouteConstraint
{
    public virtual bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (routeDirection == RouteDirection.UrlGeneration)
        {
            return true;
        }

        var slug = values["slug"] != null ? values["slug"].ToString() : null;

        if (string.IsNullOrWhiteSpace(slug))
        {
            // Homepage
            return true;
        }

        // Get category service
        var categoryService = httpContext.RequestServices.GetRequiredService<ICategoryService>();

        var category = categoryService.GetBySlug(slug);

        if (category == null)
        {
            return false;
        }

        values["controller"] = "Category";
        values["action"] = "Listing";
        values["category"] = category;

        return true;
    }
}

In PageConstraint, I look to see if the Category exists, and if it does, it changes the Controller to Category and the Action to Listing in the RouteValueDictionary. However, when I debug the code through, it still goes to the Controller Page and the Action Home.

Anyone know why this is happening, or whether there is a better way of doing this? I know I could have one action in a controller doing all the work that the constraint is, but I would prefer to house the code in separate controllers and actions.

Body:
For your requirement, you could try to implement custom IRouter

public class RouterFromAppSettings : IRouter
{
    private readonly IRouter _defaulRouter;
    private readonly IConfiguration _config;
    public RouterFromAppSettings(IRouter defaulRouter
        , IConfiguration config)
    {
        _defaulRouter = defaulRouter;
        _config = config;
    }
    public async Task RouteAsync(RouteContext context)
    {
        var controller = _config.GetSection("Router").GetValue<string>("Controller");
        var action = _config.GetSection("Router").GetValue<string>("Action");
        context.RouteData.Values["controller"] = controller;
        context.RouteData.Values["action"] = action;
        await _defaulRouter.RouteAsync(context);
    }
    public VirtualPathData GetVirtualPath(VirtualPathContext context)
    {
        return _defaulRouter.GetVirtualPath(context);
    }
}

And then register it in Startup.cs like

app.UseMvc(routes =>
{
    routes.Routes.Insert(0, new RouterFromAppSettings(routes.DefaultHandler,Configuration));

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});


问:
Segmenting boxes into different images
I am trying to read information from documents in which the data fields are of the type where you can enter only one letter/digit in a box. I managed to segment box arrays for respective data fields, however I am having problem in segmenting individual boxes in these box arrays.

I have tried to use the cv2.approxPolyDP and cv2.HoughLines functions however both give unacceptable results. The sudoku question at one point uses the fact that the length of vertical/horizontal line is much bigger than individual numbers. In my case the numbers sometimes spill out of the boxes and almost always touch the boxes.

This function is not able to detect small boxes individually:

def detect_boxes(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    sharp_img = cv2.filter2D(np.asarray(gray), -1, kernel)
    ret,thresh = cv2.threshold(sharp_img,180,255,1)
    edges = cv2.Canny(sharp_img,50,150,apertureSize = 3)
    _,contours,h = cv2.findContours(thresh,1,2)
    boxes = []
    for cnt in contours:
        approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
        temp = img
        if len(approx)==4:
            boxes.append(cnt)
            print(cnt.shape)
            print(max(cnt[0])-min(cnt[0]),max(cnt[1])-min(cnt[1]))
            cv2.drawContours(temp,[cnt],0,(0,0,255),-1)
            cv2_imshow(temp)
    return boxes
```

<p>The <code>approxPolyDP</code> result is:</p>

<p><img src="https://i.ibb.co/Lkj8vcw/poly.png" alt="approxPolyDP result"></p>

<p>The other function is:</p>

<pre class="lang-py prettyprint-override"><code>def det_box(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    sharp_img = cv2.filter2D(np.asarray(gray), -1, kernel)
    ret,thresh = cv2.threshold(sharp_img,180,255,1)
    edges = cv2.Canny(gray,50,150,apertureSize = 3)
    cv2_imshow(edges)
    lines = cv2.HoughLines(edges,1,np.pi/180,200)
    temp = img
    for rho,theta in lines[0]:
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        x1 = int(x0 + 1000*(-b))
        y1 = int(y0 + 1000*(a))
        x2 = int(x0 - 1000*(-b))
        y2 = int(y0 - 1000*(a))

        cv2.line(temp,(x1,y1),(x2,y2),(0,0,255),2)
    cv2_imshow(temp)
    return lines
</code>```

The HoughLines result is:

I was trying to get box points/contours of each individual small box in order. Any help will be appreciated. Even removing the horizontal and vertical lines in the boxes will be helpful.

答:
Took me some time but I figured it out myself.

Actual image:

```<code>if len(img.shape) != 2:
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
    gray = img

kernel = np.array([[-1,-1,-1],[-1,9,-1],[-1,-1,-1]])
sharp_img = cv2.filter2D(np.asarray(gray), -1, kernel)
gray = cv2.bitwise_not(gray)
ret,bw = cv2.threshold(sharp_img,200,255,1)

#### HORIZONTAL TRANSFORMATIONS #######
hz_kernel = np.array([[1,2,1],[0,0,0],[-1,-2,-1]])
vert_kernel = np.array([[-1,0,1],[-2,0,2],[-1,0,1]])

hz_img = cv2.filter2D(np.asarray(bw),-1,hz_kernel)
dilated = cv2.dilate(hz_img, np.ones((1, 5)),iterations = 2)
hz_img = cv2.erode(dilated,np.ones((1,5)),iterations = 4)
#cv2_imshow(bw)

print('after hz sobel->')
cv2_imshow(hz_img)
</code>```

After horizontal sobel filter:

```<code>_, contours, hierarchy = cv2.findContours(
        hz_img,
        cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
mask = np.ones(img.shape[:2], dtype="uint8") * 255
for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    if w < (img.shape[1] - 10):
        #print(w)
        cv2.drawContours(mask, [cnt], -1, 0, -1)

hz_lines = cv2.bitwise_and(hz_img, hz_img, mask=mask)
if i == 0:
    print("after removing noise")
    cv2_imshow(hz_lines)
</code>```

After horizontal noise removal:

```<code>######## VERTICAL TRANSFORMATIONS #########
vert_img = cv2.filter2D(np.asarray(bw),-1,vert_kernel)
dilated = cv2.dilate(vert_img, np.ones((3, 1)),iterations = 1)
vert_img = cv2.erode(dilated,np.ones((3,1)),iterations = 1)

print("after vertical soble->")
cv2_imshow(vert_img)
</code>```

After vertical sobel filter:

```<code>_, vert_contours, _ = cv2.findContours(
        vert_img,
        cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
vert_mask = np.ones(img.shape[:2], dtype="uint8") * 255
for cnt in vert_contours:
    x,y,w,h = cv2.boundingRect(cnt)
    if h<vert_img.shape[0]-10 or w > 5:
        #print(w)
        cv2.drawContours(vert_mask, [cnt], -1, 0, -1)

vert_lines = cv2.bitwise_and(vert_img, vert_img, mask=vert_mask)

print('after removing noise ->')
cv2_imshow(vert_lines)
</code>```

After vertical noise removal:

```<code>####### COMBINATION ##########
boxes_array = cv2.bitwise_or(vert_lines,hz_lines)

print('box array')
cv2_imshow(boxes_array)
</code>```

Bitwise or of results:

```<code>dilated = cv2.dilate(boxes_array, np.ones((7, 7)),iterations = 3)
eroded = cv2.bitwise_not(cv2.erode(dilated,np.ones((7,7)),iterations = 3))

print('dilated and inverted->')
cv2_imshow(eroded)
</code>```

After dilation, erosion and inversion:

```<code># Finally find the contours and find the bounding boxes
imz,contours,_ = cv2.findContours(
        eroded,
        cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[::-1]
boxes = []
for cnt in contours:
    rect = cv2.boundingRect(cnt)
    if rect[2]/rect[3] < 0.6 or rect[3]/rect[2] < 0.6:
        continue
    boxes.append(rect)
    num_img = img[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]]
    cv2_imshow(num)
</code>```

A box after cropping:

Title: Segmenting boxes into different images

Body:
I am trying to read information from documents in which the data fields are of the type where you can enter only one letter/digit in a box. I managed to segment box arrays for respective data fields, however I am having problem in segmenting individual boxes in these box arrays.

I have tried to use the cv2.approxPolyDP and cv2.HoughLines functions however both give unacceptable results. The sudoku question at one point uses the fact that the length of vertical/horizontal line is much bigger than individual numbers. In my case the numbers sometimes spill out of the boxes and almost always touch the boxes.

This function is not able to detect small boxes individually:

def detect_boxes(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    sharp_img = cv2.filter2D(np.asarray(gray), -1, kernel)
    ret,thresh = cv2.threshold(sharp_img,180,255,1)
    edges = cv2.Canny(sharp_img,50,150,apertureSize = 3)
    _,contours,h = cv2.findContours(thresh,1,2)
    boxes = []
    for cnt in contours:
        approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
        temp = img
        if len(approx)==4:
            boxes.append(cnt)
            print(cnt.shape)
            print(max(cnt[0])-min(cnt[0]),max(cnt[1])-min(cnt[1]))
            cv2.drawContours(temp,[cnt],0,(0,0,255),-1)
            cv2_imshow(temp)
    return boxes

The approxPolyDP result is:

The other function is:

def det_box(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    sharp_img = cv2.filter2D(np.asarray(gray), -1, kernel)
    ret,thresh = cv2.threshold(sharp_img,180,255,1)
    edges = cv2.Canny(gray,50,150,apertureSize = 3)
    cv2_imshow(edges)
    lines = cv2.HoughLines(edges,1,np.pi/180,200)
    temp = img
    for rho,theta in lines[0]:
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        x1 = int(x0 + 1000*(-b))
        y1 = int(y0 + 1000*(a))
        x2 = int(x0 - 1000*(-b))
        y2 = int(y0 - 1000*(a))

        cv2.line(temp,(x1,y1),(x2,y2),(0,0,255),2)
    cv2_imshow(temp)
    return lines

The HoughLines result is:

I was trying to get box points/contours of each individual small box in order. Any help will be appreciated. Even removing the horizontal and vertical lines in the boxes will be helpful.

Body:
Took me some time but I figured it out myself.

Actual image:

if len(img.shape) != 2:
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
    gray = img

kernel = np.array([[-1,-1,-1],[-1,9,-1],[-1,-1,-1]])
sharp_img = cv2.filter2D(np.asarray(gray), -1, kernel)
gray = cv2.bitwise_not(gray)
ret,bw = cv2.threshold(sharp_img,200,255,1)

#### HORIZONTAL TRANSFORMATIONS #######
hz_kernel = np.array([[1,2,1],[0,0,0],[-1,-2,-1]])
vert_kernel = np.array([[-1,0,1],[-2,0,2],[-1,0,1]])

hz_img = cv2.filter2D(np.asarray(bw),-1,hz_kernel)
dilated = cv2.dilate(hz_img, np.ones((1, 5)),iterations = 2)
hz_img = cv2.erode(dilated,np.ones((1,5)),iterations = 4)
#cv2_imshow(bw)

print('after hz sobel->')
cv2_imshow(hz_img)

After horizontal sobel filter:

_, contours, hierarchy = cv2.findContours(
        hz_img,
        cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
mask = np.ones(img.shape[:2], dtype="uint8") * 255
for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    if w < (img.shape[1] - 10):
        #print(w)
        cv2.drawContours(mask, [cnt], -1, 0, -1)

hz_lines = cv2.bitwise_and(hz_img, hz_img, mask=mask)
if i == 0:
    print("after removing noise")
    cv2_imshow(hz_lines)

After horizontal noise removal:

######## VERTICAL TRANSFORMATIONS #########
vert_img = cv2.filter2D(np.asarray(bw),-1,vert_kernel)
dilated = cv2.dilate(vert_img, np.ones((3, 1)),iterations = 1)
vert_img = cv2.erode(dilated,np.ones((3,1)),iterations = 1)

print("after vertical soble->")
cv2_imshow(vert_img)

After vertical sobel filter:

_, vert_contours, _ = cv2.findContours(
        vert_img,
        cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
vert_mask = np.ones(img.shape[:2], dtype="uint8") * 255
for cnt in vert_contours:
    x,y,w,h = cv2.boundingRect(cnt)
    if h<vert_img.shape[0]-10 or w > 5:
        #print(w)
        cv2.drawContours(vert_mask, [cnt], -1, 0, -1)

vert_lines = cv2.bitwise_and(vert_img, vert_img, mask=vert_mask)

print('after removing noise ->')
cv2_imshow(vert_lines)

After vertical noise removal:

####### COMBINATION ##########
boxes_array = cv2.bitwise_or(vert_lines,hz_lines)

print('box array')
cv2_imshow(boxes_array)

Bitwise or of results:

dilated = cv2.dilate(boxes_array, np.ones((7, 7)),iterations = 3)
eroded = cv2.bitwise_not(cv2.erode(dilated,np.ones((7,7)),iterations = 3))

print('dilated and inverted->')
cv2_imshow(eroded)

After dilation, erosion and inversion:

# Finally find the contours and find the bounding boxes
imz,contours,_ = cv2.findContours(
        eroded,
        cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[::-1]
boxes = []
for cnt in contours:
    rect = cv2.boundingRect(cnt)
    if rect[2]/rect[3] < 0.6 or rect[3]/rect[2] < 0.6:
        continue
    boxes.append(rect)
    num_img = img[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]]
    cv2_imshow(num)

A box after cropping:


问:
How do I perform a simple one-statement SQL search across tables?
Suppose that two tables exist: users and groups.

How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text?

The result of the search must distinguish between the two types.

答:
The trick is to combine a UNION with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice:

```<code> SELECT "group" type, name
   FROM groups
  WHERE name LIKE "%$text%"
UNION ALL
 SELECT "user" type, name
   FROM users
  WHERE name LIKE "%$text%"
</code>```

NOTE: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it.

OwnerDisplayName: Bobby Jack

ContentLicense: CC BY-SA 3.0

Body:
The trick is to combine a UNION with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice:

 SELECT "group" type, name
   FROM groups
  WHERE name LIKE "%$text%"
UNION ALL
 SELECT "user" type, name
   FROM users
  WHERE name LIKE "%$text%"

NOTE: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Bobby Jack


问:
Row counts of all pages in selenium
I have 5 pages(we are using pagination). Each page has 10 records on it.
If i use

```<code>int rcount =  selenium.getXpathCount("//table[@id='bank']/tbody/tr").intValue();
</code>```

I am getting rcount as 10, that means it is only getting the 1st page count only
I want to get all records of 5 pages(total 50 records)
Help me...

答:
You will need to loop over all the pages clicking the next button and summing the values of the row count:</p>

```<code>int rcount = selenium.getXpathCount("//table[@id='bank']/tbody/tr").intValue();
while(selenium.isElementPresent("next button locator")) {
    selenium.click("next button locator");
    selenium.waitForPageToLoad("timeout");
    rcount += selenium.getXpathCount("//table[@id='bank']/tbody/tr").intValue();
}
</code>```

Title: Row counts of all pages in selenium

Body:
I have 5 pages(we are using pagination). Each page has 10 records on it.
If i use

int rcount =  selenium.getXpathCount("//table[@id='bank']/tbody/tr").intValue();

I am getting rcount as 10, that means it is only getting the 1st page count only
I want to get all records of 5 pages(total 50 records)
Help me...

Body:
You will need to loop over all the pages clicking the next button and summing the values of the row count:

int rcount = selenium.getXpathCount("//table[@id='bank']/tbody/tr").intValue();
while(selenium.isElementPresent("next button locator")) {
    selenium.click("next button locator");
    selenium.waitForPageToLoad("timeout");
    rcount += selenium.getXpathCount("//table[@id='bank']/tbody/tr").intValue();
}


问:
How to fix SQLSyntaxErrorException?
I am Creating a Banking Management System and facing error in Deposit Class

SQLSyntaxErrorException: ORA-00933: SQL command not properly ended

The Code is:

```<code>try {
 String a = t1.getText();
 String b = t2.getText();

 if (ae.getSource() == b1) {
  if (t1.getText().equals("")) {

   JOptionPane.showMessageDialog(null, "Please enter the Amount to you want to Deposit");

  } else {

   conn c1 = new conn();

   ResultSet rs = c1.s.executeQuery(" select * from bank where pin = '" + b + "' ");

   double balance = 0;
   if (rs.next()) {
    String pin = rs.getString("pin");

    balance = rs.getDouble("balance");

    double d = Double.parseDouble(a);

    balance += d;

    String q1 = "insert into bank values('" + pin + "','" + d + "',null,'" + balance + "')";

    c1.s.executeUpdate(q1);
   }
</code>```

I have tried to resolve this problem but I am unable. The problem is that balance is not being inserted into bank table & this error is being faced by me, Please if anybody can help...

答:
Try to use insert statement like below in your oracle database table, also make sure bank table has only 4 columns</p>

```<code>String sql = "insert into bank values(?,?,?,?) ";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, pin);
pst.setString(2, d);
pst.setString(3, null);
pst.setString(4, balance);
</code>```

Title: How to fix SQLSyntaxErrorException?

Body:
I am Creating a Banking Management System and facing error in Deposit Class

SQLSyntaxErrorException: ORA-00933: SQL command not properly ended

The Code is:

try {
 String a = t1.getText();
 String b = t2.getText();

 if (ae.getSource() == b1) {
  if (t1.getText().equals("")) {

   JOptionPane.showMessageDialog(null, "Please enter the Amount to you want to Deposit");

  } else {

   conn c1 = new conn();

   ResultSet rs = c1.s.executeQuery(" select * from bank where pin = '" + b + "' ");

   double balance = 0;
   if (rs.next()) {
    String pin = rs.getString("pin");

    balance = rs.getDouble("balance");

    double d = Double.parseDouble(a);

    balance += d;

    String q1 = "insert into bank values('" + pin + "','" + d + "',null,'" + balance + "')";

    c1.s.executeUpdate(q1);
   }

I have tried to resolve this problem but I am unable. The problem is that balance is not being inserted into bank table & this error is being faced by me, Please if anybody can help...

Body:
Try to use insert statement like below in your oracle database table, also make sure bank table has only 4 columns

String sql = "insert into bank values(?,?,?,?) ";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, pin);
pst.setString(2, d);
pst.setString(3, null);
pst.setString(4, balance);


问:
How do I clear all options in a dropdown box?
My code works in IE but breaks in Safari, Firefox, and Opera. (big surprise)

```<code>document.getElementById("DropList").options.length=0;
</code>```

After searching, I've learned that it's the length=0 that it doesn't like.

I've tried ...options=null and var clear=0; ...length=clear with the same result.

I am doing this to multiple objects at a time, so I am looking for some lightweight JS code.

答:
```<code>var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
  select.options[i].remove();
}
</code>```

Hope, this code will helps you

Body:
My code works in IE but breaks in Safari, Firefox, and Opera. (big surprise)

document.getElementById("DropList").options.length=0;

After searching, I've learned that it's the length=0 that it doesn't like.

I've tried ...options=null and var clear=0; ...length=clear with the same result.

I am doing this to multiple objects at a time, so I am looking for some lightweight JS code.

Body:
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
  select.options[i].remove();
}

Hope, this code will helps you


问:
Regular Expression for matching parentheses
What is the regular expression for matching '(' in a string?

Following is the scenario :

I have a string

```<code>str = "abc(efg)";
</code>```

I want to split the string at '(' using regular expression.For that i am using

```<code>Arrays.asList(Pattern.compile("/(").split(str))
</code>```

But i am getting the following exception.

```<code>java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(
</code>```

Escaping '(' doesn't seems to work.

答: Because ( is special in regex, you should escape it \( when matching. However, depending on what language you are using, you can easily match ( with string methods like index() or other methods that enable you to find at what position the ( is in. Sometimes, there's no need to use regex.

Body:
What is the regular expression for matching '(' in a string?

Following is the scenario :

I have a string

str = "abc(efg)";

I want to split the string at '(' using regular expression.For that i am using

Arrays.asList(Pattern.compile("/(").split(str))

But i am getting the following exception.

java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(

Escaping '(' doesn't seems to work.


问:
Set UIWebView Content not to move when keyboard is shown
I've done large enough research but couldn't find answer to my question.

Suppose I have a webView in which I have some text fields, some of them are placed on the bottom of screen so that when keyboard appears it should hide that fields. After keyboard appears the content of webView slides up in order to make that fields visible. The problem is that I DON'T want the content to slide up.

Question is: How can I disable that feature of webview , or somehow make the content not scroll up.???

Thanks, any help would be appreciated.

答:
Originally I was looking to stop my webview from zooming in when an input field (in my case the comments section) was focused on. The entire view would zoom in automatically and put everything out of whack.
I managed to do it with this, and at the same time I got the webview to stop scrolling up and out of the way of the soft keyboard as well:</p>

```<code>//Stop the webview from zooming in when the comments section is used.
UIScrollView *scrollView = [_webView.subviews objectAtIndex:0];
scrollView.delegate = self;

//_webView.scrollView.delegate = self; //for versions newer than iOS5.
</code>```

Body:
Originally I was looking to stop my webview from zooming in when an input field (in my case the comments section) was focused on. The entire view would zoom in automatically and put everything out of whack.
I managed to do it with this, and at the same time I got the webview to stop scrolling up and out of the way of the soft keyboard as well:

//Stop the webview from zooming in when the comments section is used.
UIScrollView *scrollView = [_webView.subviews objectAtIndex:0];
scrollView.delegate = self;

//_webView.scrollView.delegate = self; //for versions newer than iOS5.


问:
(VS2017) There was an error running the selected code generator: 'Sequence contains no elements'
I'm running through one of Microsoft's tutorials on MVC development and I'm getting errors when trying to create various elements; Views, Controllers, etc.

The error I'm getting is the following:

```<code>There was an error running the selected code generator:
'Sequence contains no elements'
</code>```

It's consistant everytime I try to create a new element. Earlier, I bypassed the error by copying a view and repurposing it. But that's not optimal in the long run!

I'm currently sitting at work doing this tutorial where the issues arise. However, when I started this tutorial at home yesterday (hence, on a different network) I had zero issues. Might that have something to say?

Here's a link to the project on GitHub.

Do you think it's an issues with my network, my project itself, or something completely different?

答:
I had the same error in visual studio 2019.

Problem could be fixed by:

Close Visual Studio

Delete '.vs' directory

Open Project

Rebuild

Body:
I'm running through one of Microsoft's tutorials on MVC development and I'm getting errors when trying to create various elements; Views, Controllers, etc.

The error I'm getting is the following:

There was an error running the selected code generator:
'Sequence contains no elements'

It's consistant everytime I try to create a new element. Earlier, I bypassed the error by copying a view and repurposing it. But that's not optimal in the long run!

I'm currently sitting at work doing this tutorial where the issues arise. However, when I started this tutorial at home yesterday (hence, on a different network) I had zero issues. Might that have something to say?

Here's a link to the project on GitHub.

Do you think it's an issues with my network, my project itself, or something completely different?


问:
How to get the difference between two times with SQL Server?
I have the following two column with Time values

```<code>;WITH cte AS (
SELECT *
FROM (VALUES
('08:00:00','18:30:00'),
('20:00:00','08:00:00'),
('18:30:00','06:00:00'),
('08:00:00','18:30:00')) as t(time1, time2)
)
</code>```

How can I get the following difference values:

```<code>result
 10.5
  12
 11.5
 10.5
</code>```

I tried with DATEDIFF but I am never able to get a true values especially for the case from 18:30 to 6:00
I tried like this, but does not work for this case(8:30 to 6:00) ...

```<code>CASE
  WHEN GirisSaati > CikisSaati THEN cast( DATEDIFF(MINUTE, cast(CikisSaati as time ), cast(GirisSaati as time ))as float) / 60
  WHEN GirisSaati <= CikisSaati THEN  cast( DATEDIFF(MINUTE,cast( GirisSaati as time ), cast(CikisSaati as time ) )as float) /60
END
</code>```

Hope to find help, thanks ...

答:
I found another option...

Step 1 -> Create this SQL function

```<code>CREATE FUNCTION [dbo].[get_TimeDefferance_hh_mm_ss]
(
    -- Add the parameters for the function here
    @FromTime time,@ToTime time
)
RETURNS time
AS
BEGIN
    declare @totalsec decimal(10,2)= datediff(SECOND,@FromTime,@ToTime);
    declare @secondPart int= @totalsec%60
    --select @secondPart As secondpart
    declare @totalminsOnly int= (@totalsec-@secondPart)/60

declare @MinsPart int=@totalminsOnly%60
--select @MinsPart AS minsPart

declare @totalHoursOnly int= (@totalminsOnly-@MinsPart)/60

--select @totalHoursOnly AS totalhoursonly

-- Return the result of the function
RETURN cast(@totalHoursOnly AS varchar(50))+':'+cast(@MinsPart as varchar(50))+':'+cast(@secondPart as varchar(50))
</code>```

END

Step 2->Go to new query and check is it working..

```<code>declare @FromTime time='2:30:41';
declare @ToTime time='4:20:30';

declare @timeDiff time= **dbo.get_TimeDefferance_hh_mm_ss(@FromTime,@ToTime)**
select @timeDiff
</code>```

output---
01:49:49.0000000

Body:
I have the following two column with Time values

;WITH cte AS (
SELECT *
FROM (VALUES
('08:00:00','18:30:00'),
('20:00:00','08:00:00'),
('18:30:00','06:00:00'),
('08:00:00','18:30:00')) as t(time1, time2)
)

How can I get the following difference values:

result
 10.5
  12
 11.5
 10.5

I tried with DATEDIFF but I am never able to get a true values especially for the case from 18:30 to 6:00
I tried like this, but does not work for this case(8:30 to 6:00) ...

CASE
  WHEN GirisSaati > CikisSaati THEN cast( DATEDIFF(MINUTE, cast(CikisSaati as time ), cast(GirisSaati as time ))as float) / 60
  WHEN GirisSaati <= CikisSaati THEN  cast( DATEDIFF(MINUTE,cast( GirisSaati as time ), cast(CikisSaati as time ) )as float) /60
END

Hope to find help, thanks ...

Body:
I found another option...

Step 1 -> Create this SQL function

CREATE FUNCTION [dbo].[get_TimeDefferance_hh_mm_ss]
(
    -- Add the parameters for the function here
    @FromTime time,@ToTime time
)
RETURNS time
AS
BEGIN
    declare @totalsec decimal(10,2)= datediff(SECOND,@FromTime,@ToTime);
    declare @secondPart int= @totalsec%60
    --select @secondPart As secondpart
    declare @totalminsOnly int= (@totalsec-@secondPart)/60

declare @MinsPart int=@totalminsOnly%60
--select @MinsPart AS minsPart

declare @totalHoursOnly int= (@totalminsOnly-@MinsPart)/60

--select @totalHoursOnly AS totalhoursonly

-- Return the result of the function
RETURN cast(@totalHoursOnly AS varchar(50))+':'+cast(@MinsPart as varchar(50))+':'+cast(@secondPart as varchar(50))

END

Step 2->Go to new query and check is it working..

declare @FromTime time='2:30:41';
declare @ToTime time='4:20:30';

declare @timeDiff time= **dbo.get_TimeDefferance_hh_mm_ss(@FromTime,@ToTime)**
select @timeDiff

output---
01:49:49.0000000


问:
Unable to ping Private IP of DMS Replication Instance from on-premises over Site-to-Site VPN & DMS source DB endpoint test connection fails
What am I trying to do?

I want to migrate and automatically replicate data from SQL Server in my on-premises Windows Server to DB in AWS Cloud. I am using AWS DMS (Database Migration Service) for this.

What have I done/tried already?

I have set up a site-to-site VPN (between on-premises network and AWS VPC)

I am able to ping EC2 instance in VPN from Windows Server on-premises

I am able to ping Windows Server on-premises from EC2 instance in VPN

I have created a DMS Replication Instance. Its Private IP is within the allowed VPC CIDR of the VPN connection set already

I am able to ping the Private IP of DMS Replication Instance from EC2 instance

However, I am NOT able to ping the Private IP of DMS Replication Instance from Windows Server on-premises

I have set-up a DB Server in my on-premises Windows Server. I added this DB as a DMS source endpoint. When I tried to test the connection, it failed with the following error message:

I have linked a Security Group to the DMS Replication Instance. This is the same Security Group I used in the VPN connection set up
My DMS source DB endpoint configuration is as follows:

What do I want to know?

Why am I not able to ping the private IP of DMS Replication Instance while I am able to ping an EC2 instance by setting up VPN
Why the DMS endpoint test connection is failing?
Could you help me in doing this DB migration please?

答:
Probably the following debugging method would help you.

As you have mentioned that you are able to ping the EC2 instance private IP from your on-premise network, it was clear that Site-Site VPN is successful.

You did not mention that you created the DMS instance in the same subnet as the other windows instance which you are able to ping from your on-premise network. If you are created DMS in a different subnet please make sure the route table associated with that subnet has route propagation enabled . Then please check in the security groups that in the inbound rules you are allowing the port numbers and IP addresses. This way we can make sure all the things are setup proper in AWS.

From your on-premise sites please make a telnet test with the following command.

Windows/Linux:

Open command prompt in windows or terminal in linux and try

```<code>telnet <<DMS IP>> <<Port Number>>
</code>```

If it is successful connected then you have connectivity between on-premise to DMS host.

If it is not successfully connected or timed out then you need to contact your on-premise network manager or who is in-charge and tell them that you have an issue connecting with AWS Subnet x.x.x.x/x CIDR from on-premise network

Body:
Probably the following debugging method would help you.

As you have mentioned that you are able to ping the EC2 instance private IP from your on-premise network, it was clear that Site-Site VPN is successful.

You did not mention that you created the DMS instance in the same subnet as the other windows instance which you are able to ping from your on-premise network. If you are created DMS in a different subnet please make sure the route table associated with that subnet has route propagation enabled . Then please check in the security groups that in the inbound rules you are allowing the port numbers and IP addresses. This way we can make sure all the things are setup proper in AWS.

From your on-premise sites please make a telnet test with the following command.

Windows/Linux:

Open command prompt in windows or terminal in linux and try

telnet <<DMS IP>> <<Port Number>>

If it is successful connected then you have connectivity between on-premise to DMS host.

If it is not successfully connected or timed out then you need to contact your on-premise network manager or who is in-charge and tell them that you have an issue connecting with AWS Subnet x.x.x.x/x CIDR from on-premise network


问:
How can make a single get request for different sets of data?
I have 2 action which returns json data.

The first action is called with an ajax request to fill the first set of controls which remains common for the whole project but has to be filled on each menu click but the lower part of the page is variable and needs to be filled with different data.

Now what I want is to send a single request and do the 2 things in 1 get request.

```<code>public JSONRESULT GetCommonData()
{
    return JSONDATA;
}

public JSONRESULT GetVariableData()
{
    return JSONDATA;
}
</code>```

Now a single ajax call should be able to do this without sending the request for 2nd set of data.

答:
You can create a view model and you can return both 2 data in a single action. On the action you can get variables as you want.

```<code>public class JsonResult
{
    public object CommonData { get; set; }
    public object VariableData { get; set; }
}
</code>```

If you will have some relational data you might get circular reference error. You can use it like this:

```<code>var jsonResult = JsonConvert.SerializeObject(yourmodel, Formatting.Indented,
    new JsonSerializerSettings
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    });

return Json(jsonResult, JsonRequestBehavior.AllowGet);
</code>```

Body:
I have 2 action which returns json data.

The first action is called with an ajax request to fill the first set of controls which remains common for the whole project but has to be filled on each menu click but the lower part of the page is variable and needs to be filled with different data.

Now what I want is to send a single request and do the 2 things in 1 get request.

public JSONRESULT GetCommonData()
{
    return JSONDATA;
}

public JSONRESULT GetVariableData()
{
    return JSONDATA;
}

Now a single ajax call should be able to do this without sending the request for 2nd set of data.

Body:
You can create a view model and you can return both 2 data in a single action. On the action you can get variables as you want.

public class JsonResult
{
    public object CommonData { get; set; }
    public object VariableData { get; set; }
}

If you will have some relational data you might get circular reference error. You can use it like this:

var jsonResult = JsonConvert.SerializeObject(yourmodel, Formatting.Indented,
    new JsonSerializerSettings
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    });

return Json(jsonResult, JsonRequestBehavior.AllowGet);


问:
Why is $ReturnValue1 being generated when i pass (by value) a dictionary<char, stack<int>> to a function
We are creating the Towers of Hanoi game in a console window. We are supposed to use a Dictionary> to hold the game pieces. I have it declared outside of main as a global. When I call the static void function drawboard(Dictionary<char, Stack<int>>. No matter what I try, a local variable name System.Collections.Generic.Dictionary<TKey, TValue>.this[TKey].get returned. When I watch the variable it is displayed as $ReturnValue1, and it is overwriting my original dictionary. What is happening, and how do I stop it, or at least work around it.

I have tried creating clones of the dictionary and passing them through drawboard, but it still overrides the original. I have tried changing the scope of the dictionary, and I have tried adding modifiers to the dictionary like protected, private, ect. I have also jumped through several hoops and made my drawboard a little more complicated than it currently is trying to get around this problem. I can simplify it easily enough if I can figure out the root of my problem.

--declaration--

```<code> static Dictionary<char, Stack<int>> towers = new Dictionary<char, Stack<int>>();
            towers.Add('A', new Stack<int> { });
            for (int x = 4; x > 0; x--)
            {
                towers['A'].Push(x);
            }
            towers.Add('B', new Stack<int> { });
            towers.Add('C', new Stack<int> { });
</code>```

---draw board function---

```<code>static void printboard(Dictionary<char, Stack<int>> t)
    {
        Stack<int> A = t['A'];
        Stack<int> B = t['B'];
        Stack<int> C = t['C'];

        for (int y = 0; y < 5; y++)
        {
            if (y == 4)
            {
                Console.Write("----------\n" +
                              "A   B   C\n");
            }
            else
            {
                if (A.Count == 0)
                    Console.Write("|" + "   ");
                else
                {
                    Console.Write(A.Pop() + "   ");
                }
                if (B.Count == 0)
                    Console.Write("|" + "   ");
                else
                {
                    Console.Write(B.Pop() + "   ");
                }
                if (C.Count == 0)
                    Console.Write("|" + "   ");
                else
                {
                    Console.Write(C.Pop() + "   ");
                }
                Console.Write("\n");
            }
        }
    }
</code>```

The code is supposed to pass the dictionary by value, pop out values from the local copy of the dictionary and print them out to the console window, without affecting the original towers Dictionary.

答:
Create a Dictionary type variable and assign a copy of the original dictionary towers to it and then pass this new variable to your printboard method. Something like this:

```<code>var copiedTowers = new Dictionary<char, Stack<int>>(towers);
printboard(copiedTowers);
</code>```

This can also be implemented as:

```<code>printboard(new Dictionary<char, Stack<int>>(towers));
</code>```

Also, within the printboard method, while initializing the variable Stack<int> A, follow the same approach to copy contents of dictionary value. Like this:

```<code>Stack<int> A = new Stack<int>(t['A']);
Stack<int> B = new Stack<int>(t['B']);
Stack<int> C = new Stack<int>(t['C']);
</code>```

Body:
We are creating the Towers of Hanoi game in a console window. We are supposed to use a Dictionary> to hold the game pieces. I have it declared outside of main as a global. When I call the static void function drawboard(Dictionary<char, Stack<int>>. No matter what I try, a local variable name System.Collections.Generic.Dictionary<TKey, TValue>.this[TKey].get returned. When I watch the variable it is displayed as $ReturnValue1, and it is overwriting my original dictionary. What is happening, and how do I stop it, or at least work around it.

I have tried creating clones of the dictionary and passing them through drawboard, but it still overrides the original. I have tried changing the scope of the dictionary, and I have tried adding modifiers to the dictionary like protected, private, ect. I have also jumped through several hoops and made my drawboard a little more complicated than it currently is trying to get around this problem. I can simplify it easily enough if I can figure out the root of my problem.

--declaration--

 static Dictionary<char, Stack<int>> towers = new Dictionary<char, Stack<int>>();
            towers.Add('A', new Stack<int> { });
            for (int x = 4; x > 0; x--)
            {
                towers['A'].Push(x);
            }
            towers.Add('B', new Stack<int> { });
            towers.Add('C', new Stack<int> { });

---draw board function---

static void printboard(Dictionary<char, Stack<int>> t)
    {
        Stack<int> A = t['A'];
        Stack<int> B = t['B'];
        Stack<int> C = t['C'];

        for (int y = 0; y < 5; y++)
        {
            if (y == 4)
            {
                Console.Write("----------\n" +
                              "A   B   C\n");
            }
            else
            {
                if (A.Count == 0)
                    Console.Write("|" + "   ");
                else
                {
                    Console.Write(A.Pop() + "   ");
                }
                if (B.Count == 0)
                    Console.Write("|" + "   ");
                else
                {
                    Console.Write(B.Pop() + "   ");
                }
                if (C.Count == 0)
                    Console.Write("|" + "   ");
                else
                {
                    Console.Write(C.Pop() + "   ");
                }
                Console.Write("\n");
            }
        }
    }

The code is supposed to pass the dictionary by value, pop out values from the local copy of the dictionary and print them out to the console window, without affecting the original towers Dictionary.

Body:
Create a Dictionary type variable and assign a copy of the original dictionary towers to it and then pass this new variable to your printboard method. Something like this:

var copiedTowers = new Dictionary<char, Stack<int>>(towers);
printboard(copiedTowers);

This can also be implemented as:

printboard(new Dictionary<char, Stack<int>>(towers));

Also, within the printboard method, while initializing the variable Stack<int> A, follow the same approach to copy contents of dictionary value. Like this:

Stack<int> A = new Stack<int>(t['A']);
Stack<int> B = new Stack<int>(t['B']);
Stack<int> C = new Stack<int>(t['C']);


问:
I am getting this error everytime I enter new fields in "res.partner" by inheriting it in my new python file
I am writing a code to add new field in "res.partner". I searched everywhere but couldn't find the solution to this problem.

I am naming the Class "ResPartner" and inheriting "res.partner".
adding personal_id field and running and installing the module it worked fine. Now,

If:
I add a new field in that existing DB it will give me the error that
res_partner. does not exist.

BUT:
If I create a new db after I have written the new fields in python under "res.partner" and install the module in that db it will run without any error.

```<code>class ResPartner(models.Model):
    _inherit = 'res.partner'

    personal_id = fields.Char(string="Personal ID Number")
    child_name_new = fields.Integer(string="Name of the Child:")
    birth_date_child = fields.Date(string="Date of birth of child")
    admission_date_child = fields.Date(string="Date of admission")
</code>```

EXPECTED:
NO ERROR

ERROR:

```<code>File /home/braincrew/Documents/projects/odoo/odoo12/odoo/odoo/models.py", line 2765, in read
    self._read_from_database(stored, inherited)
  File "/home/braincrew/Documents/projects/odoo/odoo12/odoo/odoo/models.py", line 2892, in _read_from_database
    cr.execute(query_str, params)
  File "/home/braincrew/Documents/projects/odoo/odoo12/odoo/odoo/sql_db.py", line 148, in wrapper
    return f(self, *args, **kwargs)
  File "/home/braincrew/Documents/projects/odoo/odoo12/odoo/odoo/sql_db.py", line 225, in execute
    res = self._obj.execute(query, params)
psycopg2.ProgrammingError: column res_partner.child_name_new does not exist
LINE 1: ...nce","res_partner"."personal_id" as "personal_id","res_partn..."
</code>```

答:
Are you using any custom modules ? Because the error shows ,

```<code>psycopg2.ProgrammingError: column res_partner.loan_value does not exist
</code>```

i think the field loan_value is from a custom module , and it may the reason of the error.

Body:
I am writing a code to add new field in "res.partner". I searched everywhere but couldn't find the solution to this problem.

I am naming the Class "ResPartner" and inheriting "res.partner".
adding personal_id field and running and installing the module it worked fine. Now,

If:
I add a new field in that existing DB it will give me the error that
res_partner. does not exist.

BUT:
If I create a new db after I have written the new fields in python under "res.partner" and install the module in that db it will run without any error.

class ResPartner(models.Model):
    _inherit = 'res.partner'

    personal_id = fields.Char(string="Personal ID Number")
    child_name_new = fields.Integer(string="Name of the Child:")
    birth_date_child = fields.Date(string="Date of birth of child")
    admission_date_child = fields.Date(string="Date of admission")

EXPECTED:
NO ERROR

ERROR:

File /home/braincrew/Documents/projects/odoo/odoo12/odoo/odoo/models.py", line 2765, in read
    self._read_from_database(stored, inherited)
  File "/home/braincrew/Documents/projects/odoo/odoo12/odoo/odoo/models.py", line 2892, in _read_from_database
    cr.execute(query_str, params)
  File "/home/braincrew/Documents/projects/odoo/odoo12/odoo/odoo/sql_db.py", line 148, in wrapper
    return f(self, *args, **kwargs)
  File "/home/braincrew/Documents/projects/odoo/odoo12/odoo/odoo/sql_db.py", line 225, in execute
    res = self._obj.execute(query, params)
psycopg2.ProgrammingError: column res_partner.child_name_new does not exist
LINE 1: ...nce","res_partner"."personal_id" as "personal_id","res_partn..."

Body:
Are you using any custom modules ? Because the error shows ,

psycopg2.ProgrammingError: column res_partner.loan_value does not exist

i think the field loan_value is from a custom module , and it may the reason of the error.


问:
How do I make my react app still run with lint errors?
I am working on a React application with webpack, when I run 'npm start' it takes a long time to build, but if there are lint errors it will fail at the end of the build with 'Exit status 1' and I will need to fix the error and then run 'npm start'.

The errors are things like 'un-used var', 'line too long' etc. so they shouldn't stop the app from running, and it wastes my time to wait for it to build again.

I still want to see the lint errors, but how can I stop them from causing the build to Exit?

答:
I found several solutions at https://github.com/eslint/eslint/issues/7933 such as

```<code>npm run lint -s
</code>```

or

```<code>eslint .; exit 0
</code>```

Body:
I found several solutions at https://github.com/eslint/eslint/issues/7933 such as

npm run lint -s

or

eslint .; exit 0


问:
Calling function that stores integers in an array in C
I have a homework assignment that I need assistance with.

I have written a function that should take user input using scanf and store it into an array. It will also count the number of times an integer is entered (except 0, which terminates the program)
I am specifically having an issue calling this function within main()
Any suggestions on how to fix it?

I've tried using defining the function at the bottom, and using different variables within the function: getVals

```<code>#include <stdio.h>

#define ARRAYSIZE 20 //defines the size of the array to 20

int nVals = 0;
int getVals(int myVals[], int maxVals);
int input[ARRAYSIZE+1] = {'0'};

int getVals(int myVals[], int maxVals)
{
  for (maxVals = 0; maxVals < ARRAYSIZE; maxVals++) { //When the row is    less than ten, it will run the loop and increment the row
    printf("Please Enter up to 20 integers "); //which will allow the name to be stored in the next row
    scanf("%d", &myVals[maxVals]);

    if ((myVals[maxVals] <= 0) || (maxVals == ARRAYSIZE -1))
       return nVals;
    if (myVals[maxVals] > 0)
       nVals++;

  }
}

int main() {
  printf("This program will receive up to 20 inputs from you, and sort them from least to greatest\n\n");
  printf("Enter 0 or a negative number to exit the program.\n");

  getVals(int ARRAYSIZE, int input[ARRAYSIZE]);

  printf("You have entered %d numbers\n", nVals);
  printf("%d", input[]);
  printf("\n");
  printf("Now sorting....\n");

  return 0;
}
</code>```

答:
You should find a tutorial. They are full of code samples and you could control how simple things are done in them when unsure.

First the errors.

A function declaration just declares the function and its arguments. You use it correctly. You can have has many declaration for the same function in the same program, provided all are consistent.

A function definition contains the code for the function. A program should contain exactly one definition per function. BTW, a definition is also a declaration

A function call is where the function is used. It is no longer a declaration, and a declaration for the function must be visible before the call. You must pass existing variables consistent with the declaration.

Here you should have:

```<code>int input[ARRAYSIZE];          // declare an int array
getVals(input, ARRAYSIZE);     // call the function
</code>```

This line printf("%d", input[]); is wrong too. Arrays are not first class citizens in C language, and you can only print (or read) one element at a time. At least you should write printf("%d", input); (it as a call and not a declaration so it requires actual parameters and not formal ones). But the array would decay to a pointer to its first element (fine until there), the pointer will be converted to an int value (the address of the first element of the array) and you would print that value. Not what you want :-(

But there are other possible improvements.

nVal is a global value. Globals should be avoided unless you have a strong design reason to have one. Best practices recommend to pass parameters to function instead. So you should remove the gloval int nVals = 0 change getVals to:

```<code>int getVals(int myVals[], int maxVals)
{
    int nVals;
    for (nVals = 0; nVals < maxVals; nVals++) { //When the row is    less than ten, it will run the loop and increment the row
        printf("Please Enter up to 20 integers "); //which will allow the name   to be stored in the next row
        if (1 != scanf("%d", &myVals[nVals])) {    // ALWAYS test scanf return value
            printf("Incorrect input");
            break;
        }
        if (myVals[nVals] <= 0) {
            break;
        }
    }
    return nVals;
}
</code>```

and call it from main as:

```<code>int nVals = getVals(input, ARRAYSIZE);
</code>```

Body:
I have a homework assignment that I need assistance with.

I have written a function that should take user input using scanf and store it into an array. It will also count the number of times an integer is entered (except 0, which terminates the program)
I am specifically having an issue calling this function within main()
Any suggestions on how to fix it?

I've tried using defining the function at the bottom, and using different variables within the function: getVals

#include <stdio.h>

#define ARRAYSIZE 20 //defines the size of the array to 20

int nVals = 0;
int getVals(int myVals[], int maxVals);
int input[ARRAYSIZE+1] = {'0'};

int getVals(int myVals[], int maxVals)
{
  for (maxVals = 0; maxVals < ARRAYSIZE; maxVals++) { //When the row is    less than ten, it will run the loop and increment the row
    printf("Please Enter up to 20 integers "); //which will allow the name to be stored in the next row
    scanf("%d", &myVals[maxVals]);

    if ((myVals[maxVals] <= 0) || (maxVals == ARRAYSIZE -1))
       return nVals;
    if (myVals[maxVals] > 0)
       nVals++;

  }
}

int main() {
  printf("This program will receive up to 20 inputs from you, and sort them from least to greatest\n\n");
  printf("Enter 0 or a negative number to exit the program.\n");

  getVals(int ARRAYSIZE, int input[ARRAYSIZE]);

  printf("You have entered %d numbers\n", nVals);
  printf("%d", input[]);
  printf("\n");
  printf("Now sorting....\n");

  return 0;
}

Body:
You should find a tutorial. They are full of code samples and you could control how simple things are done in them when unsure.

First the errors.

A function declaration just declares the function and its arguments. You use it correctly. You can have has many declaration for the same function in the same program, provided all are consistent.

A function definition contains the code for the function. A program should contain exactly one definition per function. BTW, a definition is also a declaration

A function call is where the function is used. It is no longer a declaration, and a declaration for the function must be visible before the call. You must pass existing variables consistent with the declaration.

Here you should have:

int input[ARRAYSIZE];          // declare an int array
getVals(input, ARRAYSIZE);     // call the function

This line printf("%d", input[]); is wrong too. Arrays are not first class citizens in C language, and you can only print (or read) one element at a time. At least you should write printf("%d", input); (it as a call and not a declaration so it requires actual parameters and not formal ones). But the array would decay to a pointer to its first element (fine until there), the pointer will be converted to an int value (the address of the first element of the array) and you would print that value. Not what you want :-(

But there are other possible improvements.

nVal is a global value. Globals should be avoided unless you have a strong design reason to have one. Best practices recommend to pass parameters to function instead. So you should remove the gloval int nVals = 0 change getVals to:

int getVals(int myVals[], int maxVals)
{
    int nVals;
    for (nVals = 0; nVals < maxVals; nVals++) { //When the row is    less than ten, it will run the loop and increment the row
        printf("Please Enter up to 20 integers "); //which will allow the name   to be stored in the next row
        if (1 != scanf("%d", &myVals[nVals])) {    // ALWAYS test scanf return value
            printf("Incorrect input");
            break;
        }
        if (myVals[nVals] <= 0) {
            break;
        }
    }
    return nVals;
}

and call it from main as:

int nVals = getVals(input, ARRAYSIZE);


问:
c# file move (file is already used by another process)
I am moving files from one folder to another. If I try to move the entire folder to the folder within that particular folder I cannot do that. But if I move it outside it works fine. How can I move my folder to the folder within that folder?

this gives error

```<code>  if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\copypath\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }
</code>```

this works fine

```<code> if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }
</code>```

答:
It throws away the error, because you are trying to move a directory in its own subdirectory. This would give an error in windows as well...

You can do this as an alternate, if you are trying to copy rather than move...

```<code>if (System.IO.Directory.Exists(PhysicalPath))
{
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\copypath\\abc\\";
      System.IO.Directory.Copy(sourcePath, targetPath);
}
</code>```

Body:
I am moving files from one folder to another. If I try to move the entire folder to the folder within that particular folder I cannot do that. But if I move it outside it works fine. How can I move my folder to the folder within that folder?

this gives error

  if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\copypath\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }

this works fine

 if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }

Body:
It throws away the error, because you are trying to move a directory in its own subdirectory. This would give an error in windows as well...

You can do this as an alternate, if you are trying to copy rather than move...

if (System.IO.Directory.Exists(PhysicalPath))
{
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\copypath\\abc\\";
      System.IO.Directory.Copy(sourcePath, targetPath);
}


问:
Problem loading a flat file into a data frame from Azure Data Lake
I wrote Python to load data from Azure Data Lake into a data frame for processing.  I have two file types (CSV and flat files).  The CSV loads without a problem, but the flat file errors out.

I know it is an issue with the file format.  It gives a type error: a bytes-like object is required, not 'str'

I cannot figure out how to convert the file to make it work properly.  Ive tried encoding and decoding, but I ran into an attribute error : 'AzureDLFile' object has no attribute 'decode'

When I tested the script locally on my C:\ drive it works fine, so I suspect the file coming out of Azure is different.  Does anyone have any ideas on how to convert the file so I can bring it in?

```<code>import numpy as np
import pandas as pd
import datetime
import os

from azure.datalake.store import core, lib, multithread

USERNAME = "xxxx"
PASSWORD = "xxxx"
TENANT_ID = "xxxx"
STORE_NAME = "xxxx"

token = lib.auth(TENANT_ID, USERNAME, PASSWORD)
adl = core.AzureDLFileSystem(token, store_name=STORE_NAME)

#EXAMPLE 1 - OPENING A CSV FILE INTO A DATA FRAME - WORKS FINE
f = adl.open('/path/filename1.txt')
df = pd.read_csv(f,dtype=str, sep='|')
df[:3]

#EXAMPLE 2 - OPENING A FLAT FIXED WIDTH FILE INTO A DATA FRAME - DOES NOT WORK
f1 = adl.open('/path/filename2') #THIS FILE HAS NO EXTENSION
df2 = pd.read_fwf(f1)
df2[:3]
</code>```

答:
Key is converting the dataframe to a string and than using the str.encode() function.

Try something like below

```<code>adl = core.AzureDLFileSystem(token, store_name='YOUR_ADLS_STORE_NAME')
      #toke is your login token that was created by whatever ADLS login method you decided.
      #Personally I use the ServiceProvider login
df_str = df.to_csv()
**with adl.open('/path/to/file/on/adls/newfile.csv', 'wb') as f:
    f.write(str.encode(df_str))
    f.close()**
</code>```

Hope it helps.

Body:
I wrote Python to load data from Azure Data Lake into a data frame for processing.  I have two file types (CSV and flat files).  The CSV loads without a problem, but the flat file errors out.

I know it is an issue with the file format.  It gives a type error: a bytes-like object is required, not 'str'

I cannot figure out how to convert the file to make it work properly.  Ive tried encoding and decoding, but I ran into an attribute error : 'AzureDLFile' object has no attribute 'decode'

When I tested the script locally on my C:\ drive it works fine, so I suspect the file coming out of Azure is different.  Does anyone have any ideas on how to convert the file so I can bring it in?

import numpy as np
import pandas as pd
import datetime
import os

from azure.datalake.store import core, lib, multithread

USERNAME = "xxxx"
PASSWORD = "xxxx"
TENANT_ID = "xxxx"
STORE_NAME = "xxxx"

token = lib.auth(TENANT_ID, USERNAME, PASSWORD)
adl = core.AzureDLFileSystem(token, store_name=STORE_NAME)

#EXAMPLE 1 - OPENING A CSV FILE INTO A DATA FRAME - WORKS FINE
f = adl.open('/path/filename1.txt')
df = pd.read_csv(f,dtype=str, sep='|')
df[:3]

#EXAMPLE 2 - OPENING A FLAT FIXED WIDTH FILE INTO A DATA FRAME - DOES NOT WORK
f1 = adl.open('/path/filename2') #THIS FILE HAS NO EXTENSION
df2 = pd.read_fwf(f1)
df2[:3]

Body:
Key is converting the dataframe to a string and than using the str.encode() function.

Try something like below

adl = core.AzureDLFileSystem(token, store_name='YOUR_ADLS_STORE_NAME')
      #toke is your login token that was created by whatever ADLS login method you decided.
      #Personally I use the ServiceProvider login
df_str = df.to_csv()
**with adl.open('/path/to/file/on/adls/newfile.csv', 'wb') as f:
    f.write(str.encode(df_str))
    f.close()**

Hope it helps.


问:
Remove items in a list based on a list of substrings in another list in python3.x
I am trying to subset a list of strings based on another list of substrings. I want to remove strings in list1 if the string includes a substring in list2.

```<code>list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']

list2 = ['lunch','noon']
</code>```

The output I want:

```<code>output = ['sandwich shop','grocery store']
</code>```

答:
So many different ways to do this. Here is my approach (may not be the best).

```<code>list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']
list2 = ['lunch','noon']

list3 = [x for x in list1 if len(set(list2) & set(x.split())) == 0]

print(list3)
</code>```

Gives you:

```<code>['sandwich shop', 'grocery store']
</code>```

What is happening?

Loop through the first list items.

Convert the item to an array of words using split().

Convert that array and list2 to a set.

Do a set union to find which are similar.

Count how many were similar using len().

If nothing was similar, then add the item from list1 to list3.

Repeat until no more items.

Body:
I am trying to subset a list of strings based on another list of substrings. I want to remove strings in list1 if the string includes a substring in list2.

list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']

list2 = ['lunch','noon']

The output I want:

output = ['sandwich shop','grocery store']

Body:
So many different ways to do this. Here is my approach (may not be the best).

list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']
list2 = ['lunch','noon']

list3 = [x for x in list1 if len(set(list2) & set(x.split())) == 0]

print(list3)

Gives you:

['sandwich shop', 'grocery store']

What is happening?

Loop through the first list items.

Convert the item to an array of words using split().

Convert that array and list2 to a set.

Do a set union to find which are similar.

Count how many were similar using len().

If nothing was similar, then add the item from list1 to list3.

Repeat until no more items.


问:
Adminlte in Laravel sidebar update label on runtime
This is my menu array format in adminlte.php

```<code>'menu' => [
        [
            'text' => 'Dashboard',
            'url'  => '/dashboard',
            'icon' => 'dashboard',
            'label'=> $test // how to pass variable here or alternative way without using building menu
            'label-color' => 'success'
        ],
],
</code>```

How can I pass count variable to the label on runtime?

I knew there is a way to do it with building menu but, need to rebuild the whole thing inside adminlte.php . I need to pass count variable to it, if I put in adminlte.php, the variable will be undefined.

Can the building menu used to update the menu label or append the label and label-color into it?

Is there a method to override the current value in label by passing variable to it?

答:
From Laravel-AdminLTE documentation:

It is also possible to configure the menu at runtime, e.g. in the boot of any service provider. Use this if your menu is not static, for example when it depends on your database or the locale. It is also possible to combine both approaches. The menus will simply be concatenated and the order of service providers determines the order in the menu.

To configure the menu at runtime, register a handler or callback for the MenuBuilding event, for example in the boot() method of a service provider:

```<code>use Illuminate\Contracts\Events\Dispatcher;
use JeroenNoten\LaravelAdminLte\Events\BuildingMenu;

class AppServiceProvider extends ServiceProvider
{

    public function boot(Dispatcher $events)
    {
        $events->listen(BuildingMenu::class, function (BuildingMenu $event) {
            $event->menu->add('MAIN NAVIGATION');
            $event->menu->add([
                'text' => 'Blog',
                'url' => 'admin/blog',
            ]);
        });
    }

}
</code>```

https://github.com/jeroennoten/Laravel-AdminLTE#menu-configuration-at-runtime

Body:
This is my menu array format in adminlte.php

'menu' => [
        [
            'text' => 'Dashboard',
            'url'  => '/dashboard',
            'icon' => 'dashboard',
            'label'=> $test // how to pass variable here or alternative way without using building menu
            'label-color' => 'success'
        ],
],

How can I pass count variable to the label on runtime?

I knew there is a way to do it with building menu but, need to rebuild the whole thing inside adminlte.php . I need to pass count variable to it, if I put in adminlte.php, the variable will be undefined.

Can the building menu used to update the menu label or append the label and label-color into it?

Is there a method to override the current value in label by passing variable to it?

Body:
From Laravel-AdminLTE documentation:

It is also possible to configure the menu at runtime, e.g. in the boot of any service provider. Use this if your menu is not static, for example when it depends on your database or the locale. It is also possible to combine both approaches. The menus will simply be concatenated and the order of service providers determines the order in the menu.

To configure the menu at runtime, register a handler or callback for the MenuBuilding event, for example in the boot() method of a service provider:

use Illuminate\Contracts\Events\Dispatcher;
use JeroenNoten\LaravelAdminLte\Events\BuildingMenu;

class AppServiceProvider extends ServiceProvider
{

    public function boot(Dispatcher $events)
    {
        $events->listen(BuildingMenu::class, function (BuildingMenu $event) {
            $event->menu->add('MAIN NAVIGATION');
            $event->menu->add([
                'text' => 'Blog',
                'url' => 'admin/blog',
            ]);
        });
    }

}

https://github.com/jeroennoten/Laravel-AdminLTE#menu-configuration-at-runtime


问:
Laravel where query for getting record if the difference of two fields is not 0
I need to get record only if subtraction of two fields is not zero.

```<code>$list = InspectionCertificate::where('amount' - 'billed_amount' != 0)
</code>```

Thanks in advance.

答:
Here is the sample code for that with Eloquent Model

```<code>$list = InspectionCertificate::whereRaw('(amount - billed_amount) > 0')->get();
</code>```

You can use whereRaw to pass raw query in Query Builder.

Body:
I need to get record only if subtraction of two fields is not zero.

$list = InspectionCertificate::where('amount' - 'billed_amount' != 0)

Thanks in advance.

Body:
Here is the sample code for that with Eloquent Model

$list = InspectionCertificate::whereRaw('(amount - billed_amount) > 0')->get();

You can use whereRaw to pass raw query in Query Builder.