问:
UIAlertController custom font, size, color
I am using new UIAlertController for showing alerts. I have this code:

```<code>// nil titles break alert interface on iOS 8.0, so we'll be using empty strings
UIAlertController *alert = [UIAlertController alertControllerWithTitle: title == nil ? @"": title message: message preferredStyle: UIAlertControllerStyleAlert];

UIAlertAction *defaultAction = [UIAlertAction actionWithTitle: cancelButtonTitle style: UIAlertActionStyleCancel handler: nil];

[alert addAction: defaultAction];

UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
[rootViewController presentViewController:alert animated:YES completion:nil];
</code>```

Now I want to change title and message font, color, size and so. What's best way to do this?

Edit:
I should insert whole code. I created category for UIView that I could show right alert for iOS version.

```<code>@implementation UIView (AlertCompatibility)

+( void )showSimpleAlertWithTitle:( NSString * )title
                          message:( NSString * )message
                cancelButtonTitle:( NSString * )cancelButtonTitle
{
    float iOSVersion = [[UIDevice currentDevice].systemVersion floatValue];
    if (iOSVersion < 8.0f)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
                                                        message: message
                                                       delegate: nil
                                              cancelButtonTitle: cancelButtonTitle
                                              otherButtonTitles: nil];
        [alert show];
    }
    else
    {
        // nil titles break alert interface on iOS 8.0, so we'll be using empty strings
        UIAlertController *alert = [UIAlertController alertControllerWithTitle: title == nil ? @"": title
                                                                       message: message
                                                                preferredStyle: UIAlertControllerStyleAlert];

        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle: cancelButtonTitle
                                                                style: UIAlertActionStyleCancel
                                                              handler: nil];

        [alert addAction: defaultAction];

        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        [rootViewController presentViewController:alert animated:YES completion:nil];
    }
}
</code>```

答:
Swift 5 and 5.1. Create a separate file and put UIAlertController Customization code there

```<code>import Foundation
import  UIKit

extension UIAlertController {

  //Set background color of UIAlertController
  func setBackgroudColor(color: UIColor) {
    if let bgView = self.view.subviews.first,
      let groupView = bgView.subviews.first,
      let contentView = groupView.subviews.first {
      contentView.backgroundColor = color
    }
  }

  //Set title font and title color
  func setTitle(font: UIFont?, color: UIColor?) {
    guard let title = self.title else { return }
    let attributeString = NSMutableAttributedString(string: title)//1
    if let titleFont = font {
      attributeString.addAttributes([NSAttributedString.Key.font : titleFont],//2
        range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributeString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor],//3
        range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributeString, forKey: "attributedTitle")//4
  }

  //Set message font and message color
  func setMessage(font: UIFont?, color: UIColor?) {
    guard let title = self.message else {
      return
    }
    let attributedString = NSMutableAttributedString(string: title)
    if let titleFont = font {
      attributedString.addAttributes([NSAttributedString.Key.font : titleFont], range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributedString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor], range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributedString, forKey: "attributedMessage")//4
  }

  //Set tint color of UIAlertController
  func setTint(color: UIColor) {
    self.view.tintColor = color
  }
}
</code>```

Now On any action Show Alert

```<code>  func tapShowAlert(sender: UIButton) {
    let alertController = UIAlertController(title: "Alert!!", message: "This is custom alert message", preferredStyle: .alert)
    // Change font and color of title
    alertController.setTitle(font: UIFont.boldSystemFont(ofSize: 26), color: UIColor.yellow)
    // Change font and color of message
    alertController.setMessage(font: UIFont(name: "AvenirNextCondensed-HeavyItalic", size: 18), color: UIColor.red)
    // Change background color of UIAlertController
    alertController.setBackgroudColor(color: UIColor.black)
    let actnOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
    let actnCancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(actnOk)
    alertController.addAction(actnCancel)
    self.present(alertController, animated: true, completion: nil)
  }
</code>```

Result

Body:
I am using new UIAlertController for showing alerts. I have this code:

// nil titles break alert interface on iOS 8.0, so we'll be using empty strings
UIAlertController *alert = [UIAlertController alertControllerWithTitle: title == nil ? @"": title message: message preferredStyle: UIAlertControllerStyleAlert];

UIAlertAction *defaultAction = [UIAlertAction actionWithTitle: cancelButtonTitle style: UIAlertActionStyleCancel handler: nil];

[alert addAction: defaultAction];

UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
[rootViewController presentViewController:alert animated:YES completion:nil];

Now I want to change title and message font, color, size and so. What's best way to do this?

Edit:
I should insert whole code. I created category for UIView that I could show right alert for iOS version.

@implementation UIView (AlertCompatibility)

+( void )showSimpleAlertWithTitle:( NSString * )title
                          message:( NSString * )message
                cancelButtonTitle:( NSString * )cancelButtonTitle
{
    float iOSVersion = [[UIDevice currentDevice].systemVersion floatValue];
    if (iOSVersion < 8.0f)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
                                                        message: message
                                                       delegate: nil
                                              cancelButtonTitle: cancelButtonTitle
                                              otherButtonTitles: nil];
        [alert show];
    }
    else
    {
        // nil titles break alert interface on iOS 8.0, so we'll be using empty strings
        UIAlertController *alert = [UIAlertController alertControllerWithTitle: title == nil ? @"": title
                                                                       message: message
                                                                preferredStyle: UIAlertControllerStyleAlert];

        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle: cancelButtonTitle
                                                                style: UIAlertActionStyleCancel
                                                              handler: nil];

        [alert addAction: defaultAction];

        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        [rootViewController presentViewController:alert animated:YES completion:nil];
    }
}

Body:
Swift 5 and 5.1. Create a separate file and put UIAlertController Customization code there

import Foundation
import  UIKit

extension UIAlertController {

  //Set background color of UIAlertController
  func setBackgroudColor(color: UIColor) {
    if let bgView = self.view.subviews.first,
      let groupView = bgView.subviews.first,
      let contentView = groupView.subviews.first {
      contentView.backgroundColor = color
    }
  }

  //Set title font and title color
  func setTitle(font: UIFont?, color: UIColor?) {
    guard let title = self.title else { return }
    let attributeString = NSMutableAttributedString(string: title)//1
    if let titleFont = font {
      attributeString.addAttributes([NSAttributedString.Key.font : titleFont],//2
        range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributeString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor],//3
        range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributeString, forKey: "attributedTitle")//4
  }

  //Set message font and message color
  func setMessage(font: UIFont?, color: UIColor?) {
    guard let title = self.message else {
      return
    }
    let attributedString = NSMutableAttributedString(string: title)
    if let titleFont = font {
      attributedString.addAttributes([NSAttributedString.Key.font : titleFont], range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributedString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor], range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributedString, forKey: "attributedMessage")//4
  }

  //Set tint color of UIAlertController
  func setTint(color: UIColor) {
    self.view.tintColor = color
  }
}

Now On any action Show Alert

  func tapShowAlert(sender: UIButton) {
    let alertController = UIAlertController(title: "Alert!!", message: "This is custom alert message", preferredStyle: .alert)
    // Change font and color of title
    alertController.setTitle(font: UIFont.boldSystemFont(ofSize: 26), color: UIColor.yellow)
    // Change font and color of message
    alertController.setMessage(font: UIFont(name: "AvenirNextCondensed-HeavyItalic", size: 18), color: UIColor.red)
    // Change background color of UIAlertController
    alertController.setBackgroudColor(color: UIColor.black)
    let actnOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
    let actnCancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(actnOk)
    alertController.addAction(actnCancel)
    self.present(alertController, animated: true, completion: nil)
  }

Result


来源: stackexchange

问:
how how iloc[:,1:] works ? can any one explain [:,1:] params
What is the meaning of below lines., especially confused about how iloc[:,1:] is working ? and also data[:,:1]

```<code>data = np.asarray(train_df_mv_norm.iloc[:,1:])
X, Y = data[:,1:],data[:,:1]
</code>```

Here train_df_mv_norm is a dataframe --

答:
To complete the answer by KeyMaker00, I add that data[:,:1] means:

The first : - take all rows.

:1 - equal to 0:1 take columns starting from column 0,
up to (excluding) column 1.

So, to sum up, the second expression reads only the first column from data.

As your expression has the form:

```<code><variable_list> = <expression_list>
</code>```

each expression is substituted under the corresponding variable (X and Y).

ContentLicense: CC BY-SA 4.0

Body:
What is the meaning of below lines., especially confused about how iloc[:,1:] is working ? and also data[:,:1]

data = np.asarray(train_df_mv_norm.iloc[:,1:])
X, Y = data[:,1:],data[:,:1]

Here train_df_mv_norm is a dataframe --

Body:
To complete the answer by KeyMaker00, I add that data[:,:1] means:

The first : - take all rows.

:1 - equal to 0:1 take columns starting from column 0,
up to (excluding) column 1.

So, to sum up, the second expression reads only the first column from data.

As your expression has the form:

<variable_list> = <expression_list>

each expression is substituted under the corresponding variable (X and Y).


问:
Can I use the "skills" word to label my product extensions?
We are developing a SaaS product that can be extended by developing add-ons or plug-ins. We are calling those extensions "skills", exactly the same way Amazon's Alexa calls its extensions. Our product is completely unrelated to Alexa or Amazon, but we started using the "skills" word from the beginning and it stuck.

I've been trying to find through all the Amazon Echo and Alexa legalese but haven't been able to find anything related to using the word "skill" to represent an extension of a software product.

We are a U.S. based company. Could we get in trouble in the future because of this, or is "skill" considered a broad word that we can use without incurring in any trademark violations?

答:
From purely logical speculation, it must be open for use.

Even Alexa Skills are always specified as just that: "Alexa Skills". Similar to how the word "App" is generic and you can specify "Amazon App", "Android App", or "iOS App".
In fact, Apple even tried and failed to trademark the term "App Store". 2011 Article.

And Apple has a long list of trademarks found here.

Amazon has a trademark list as well, and is "non-exhaustive" like Apple's, to mean that there may be more. They do own:

ALEXA

  ALEXA FUND

  ALEXA GADGETS

  ALEXA ONBOARD

  ALEXA PRIZE

But the word "skill" doesn't even appear anywhere on the list, not even as "Alexa Skill" nor "Amazon Skill".

So it looks safe, but if you want a definite answer, contact a trademark lawyer to look into it. I don't think we can offer a concrete answer here. And even a trademark lawyer probably won't give you the crystal ball answer to whether Amazon will try to trademark "skill" in the future or not. But that's why I included the anecdote about Apple's attempt with "app store". Even if they try, it's probably unlikely they'll succeed.


问:
Sending Mail with Sendmail Driver not Working and No Errors Laravel 5.5
I'm trying to send emails with sendmail driver but it isn't working and I got no errors.

My .env file:

```<code>MAIL_DRIVER=sendmail
MAIL_HOST=
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
</code>```

My mail.php file:

```<code><?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    'driver' => env('MAIL_DRIVER', 'sendmail'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', ''),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'no-reply@domainexample.com'),
        'name' => env('MAIL_FROM_NAME', 'INSP Virtual'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME', null),

    'password' => env('MAIL_PASSWORD', null),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];
</code>```

Since I got no errors, even in laravel.log file I don't know even where to start checking, I have checked for the correct sendmail path though, and it was correct, what am I missing?

I also read that you have to change some things in /etc/hosts I changed it a bit adding "domainexample.com":

```<code>127.0.0.1   domainexample.com localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
</code>```

Is this last thing correct?

答:
The MAIL_USERNAME and MAIL_PASSWORD values in your .env file should be set to your sendmail authentication details as laravel required authentication from the mail client to send the mails.</p>

```<code>MAIL_USERNAME=email@sendmail.com
MAIL_PASSWORD=XXXXXXXXXX
</code>```

Body:
I'm trying to send emails with sendmail driver but it isn't working and I got no errors.

My .env file:

MAIL_DRIVER=sendmail
MAIL_HOST=
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

My mail.php file:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    'driver' => env('MAIL_DRIVER', 'sendmail'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', ''),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'no-reply@domainexample.com'),
        'name' => env('MAIL_FROM_NAME', 'INSP Virtual'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME', null),

    'password' => env('MAIL_PASSWORD', null),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

Since I got no errors, even in laravel.log file I don't know even where to start checking, I have checked for the correct sendmail path though, and it was correct, what am I missing?

I also read that you have to change some things in /etc/hosts I changed it a bit adding "domainexample.com":

127.0.0.1   domainexample.com localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

Is this last thing correct?

Body:
The MAIL_USERNAME and MAIL_PASSWORD values in your .env file should be set to your sendmail authentication details as laravel required authentication from the mail client to send the mails.

MAIL_USERNAME=email@sendmail.com
MAIL_PASSWORD=XXXXXXXXXX


问:
Twitter4J Android Search Query Returns Null
I'm trying to develop an android application, and for my purpose, I've to be able to search tweets based on the Hashtag the user searches. I'm using Twitter4j Library and I have also Consumer API key/Secret and tokens.

What I've tried so far:

```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        mTextMessage = findViewById(R.id.message);
        navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        // Twitter 4j 25.May.2019 only for test right now
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setDebugEnabled(true)
                .setOAuthConsumerKey("ABC")
                .setOAuthConsumerSecret("ABC")
                .setOAuthAccessToken("ABC")
                .setOAuthAccessTokenSecret("ABC");

        TwitterFactory tf = new TwitterFactory(configurationBuilder.build());
        final Twitter twitter = tf.getInstance();
        Query query = new Query("twitter4j");
        try {
            QueryResult result = twitter.search(query);
            for (Status status : result.getTweets()) {
                System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
            }
        } catch (TwitterException te) {
            System.out.println(te.getMessage());
        }
</code>```

I expect some JSON request from Twitter, but on my console it shows nothing.

答:
The problem wasn't with the code, or with Twitter4j library, the problem was with Network configuration, specifically with "NetworkOnMainThreadException".

To fix the issue see here: How do I fix android.os.NetworkOnMainThreadException?

Body:
I'm trying to develop an android application, and for my purpose, I've to be able to search tweets based on the Hashtag the user searches. I'm using Twitter4j Library and I have also Consumer API key/Secret and tokens.

What I've tried so far:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        mTextMessage = findViewById(R.id.message);
        navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        // Twitter 4j 25.May.2019 only for test right now
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.setDebugEnabled(true)
                .setOAuthConsumerKey("ABC")
                .setOAuthConsumerSecret("ABC")
                .setOAuthAccessToken("ABC")
                .setOAuthAccessTokenSecret("ABC");

        TwitterFactory tf = new TwitterFactory(configurationBuilder.build());
        final Twitter twitter = tf.getInstance();
        Query query = new Query("twitter4j");
        try {
            QueryResult result = twitter.search(query);
            for (Status status : result.getTweets()) {
                System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
            }
        } catch (TwitterException te) {
            System.out.println(te.getMessage());
        }

I expect some JSON request from Twitter, but on my console it shows nothing.


问:
android:singleton instance not garbage collected after application is closed
I have an android activity with a fragment.

In the fragment, I fetch data using retrofit and set a static flag, so that , when I again go to this fragment, I restrict fetching data again.

I also store the data in a singleton instance.

But even after I destroyed the activity/closed the application, the static flag and the instance is still available and the list is also present in the instance, which malfunctions my app.

But I want the instance to be created newly and fetch data at each run.

This is my singleton instance.

```<code>public class Utilities {

    private static Utilities utils = null;

    private List<Data> friendsList;

    public List<Data> getDataList() {
        return dataList;
    }

    public void setDataList(List<Data> dataList) {
        this.dataList = dataList;
    }

    private List<Data> dataList;

    public synchronized static Utilities getInstance(){

        if(utils == null){
            utils = new Utilities();
        }
        return utils;
    }
}
</code>```

This is my fragment:

```<code>public class DataFragment extends Fragment
{
    private static boolean hasObtainedData;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)  {

        if(!hasObtainedData){
            getData(v);
        }else{
           recyclerView.setAdapter(new Adapter(utils.getDataList()));
         }
     }

     private void getData(View v) {

         //get Data using Retrofit:
         hasObtainedData = true;
         utils.setDataList(dataListObtainedUsingRetrofit)
         recyclerView.setAdapter(new Adapter(utils.getDataList()));
    }
}
</code>```

This is how, I call my fragment from MainActivity:

```<code>@Override
public void onTabSelected(TabLayout.Tab tab) {
           getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fragmentBox, new DataFragment()).commit();
    }
</code>```

I tried giving System.gc() at onDestroy() of MainActivity, but still, the singleton instance is alive.

I search many SOF posts based on this, but wasn't able to solve this issue.

Any help will be really useful.

答:
Your singleton wont survive your app being terminated, and what's probably happening is that you aren't actually killing the app entirely during your tests. Run adb shell am force-stop <your-app-package> from your console and see whether that still results in the issue.

With that said, if you only want your data to run once per application launch, then I would recommend you move it into the onCreate() lifecycle callback of your Application

```<code>public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //Begin process to fetch data and cache it here
    }
}
</code>```

Don't forget to add the application name to your manifest too, <application android:name="your.packagename.App"

You then have no need to modify your data at all - it will only run once per application launch.

If, however, what you actually want is for your data to update every time the Activity is launched, then do the same process as before but inside onCreate() of you Activity. You can also clear it in onDestroy(), if you want it to updated when your Activity is recreated:

```<code>@Override
public void onDestry() {
    super.onDestroy();
    Utilities.getInstance().setDataList(null);
}
</code>```

Also, if your data is bound to the lifecycle of your Activity, then you don't really need a singleton (which is bound to the lifecycle of the application).

Body:
I have an android activity with a fragment.

In the fragment, I fetch data using retrofit and set a static flag, so that , when I again go to this fragment, I restrict fetching data again.

I also store the data in a singleton instance.

But even after I destroyed the activity/closed the application, the static flag and the instance is still available and the list is also present in the instance, which malfunctions my app.

But I want the instance to be created newly and fetch data at each run.

This is my singleton instance.

public class Utilities {

    private static Utilities utils = null;

    private List<Data> friendsList;

    public List<Data> getDataList() {
        return dataList;
    }

    public void setDataList(List<Data> dataList) {
        this.dataList = dataList;
    }

    private List<Data> dataList;

    public synchronized static Utilities getInstance(){

        if(utils == null){
            utils = new Utilities();
        }
        return utils;
    }
}

This is my fragment:

public class DataFragment extends Fragment
{
    private static boolean hasObtainedData;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)  {

        if(!hasObtainedData){
            getData(v);
        }else{
           recyclerView.setAdapter(new Adapter(utils.getDataList()));
         }
     }

     private void getData(View v) {

         //get Data using Retrofit:
         hasObtainedData = true;
         utils.setDataList(dataListObtainedUsingRetrofit)
         recyclerView.setAdapter(new Adapter(utils.getDataList()));
    }
}

This is how, I call my fragment from MainActivity:

@Override
public void onTabSelected(TabLayout.Tab tab) {
           getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fragmentBox, new DataFragment()).commit();
    }

I tried giving System.gc() at onDestroy() of MainActivity, but still, the singleton instance is alive.

I search many SOF posts based on this, but wasn't able to solve this issue.

Any help will be really useful.

Body:
Your singleton wont survive your app being terminated, and what's probably happening is that you aren't actually killing the app entirely during your tests. Run adb shell am force-stop <your-app-package> from your console and see whether that still results in the issue.

With that said, if you only want your data to run once per application launch, then I would recommend you move it into the onCreate() lifecycle callback of your Application

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //Begin process to fetch data and cache it here
    }
}

Don't forget to add the application name to your manifest too, <application android:name="your.packagename.App"

You then have no need to modify your data at all - it will only run once per application launch.

If, however, what you actually want is for your data to update every time the Activity is launched, then do the same process as before but inside onCreate() of you Activity. You can also clear it in onDestroy(), if you want it to updated when your Activity is recreated:

@Override
public void onDestry() {
    super.onDestroy();
    Utilities.getInstance().setDataList(null);
}

Also, if your data is bound to the lifecycle of your Activity, then you don't really need a singleton (which is bound to the lifecycle of the application).


问:
Can I define a custom compare function for redis zset?
Background:

I'm now using php+redis as my backend to store a rank.
And zset seems to be a good solution to handle this.
However the rank contains multiple scores, if the first score equals, I need to compare the second score to decide the ordering. There are 3 scores in total.

I thought there will be an interface that I can set a custom compare function for a specific zset so that I can do the sort job inside it but I failed to find it. Besides, I'd like the rank to be sorted when it's added. if I need to sort again everytime there is a request to get the rank, then this is wasteful I think.

expect result:

```<code>zadd myset 1000_100_3000 matchId1
zadd myset 1000_2500_250 matchId2
zadd myset 1000_2500_200 matchId3
</code>```

zrange myset 0 -1 returns:

```<code>matchId2
matchId3
matchId1
</code>```

something like this

答:
Short answer: no, you can't do that

However, you can often compose multiple keys in such a way to make them sortable. In your case, an obvious candidate would be to determine the max range of the three pieces, and just compose them all into a single big number. For example, 1000_100_3000 could perhaps be the number 100001003000 (4 decimal digits per chunk), which can be trivially compared or decomposed. You might also want to think in terms of bits rather than digits, though. For example, maybe allow 20 bits per segment, and use shift/mask bit operations to compose/decompose (i.e. (1000 << 40) | (100 << 20) | (3000))

Body:
Background:

I'm now using php+redis as my backend to store a rank.
And zset seems to be a good solution to handle this.
However the rank contains multiple scores, if the first score equals, I need to compare the second score to decide the ordering. There are 3 scores in total.

I thought there will be an interface that I can set a custom compare function for a specific zset so that I can do the sort job inside it but I failed to find it. Besides, I'd like the rank to be sorted when it's added. if I need to sort again everytime there is a request to get the rank, then this is wasteful I think.

expect result:

zadd myset 1000_100_3000 matchId1
zadd myset 1000_2500_250 matchId2
zadd myset 1000_2500_200 matchId3

zrange myset 0 -1 returns:

matchId2
matchId3
matchId1

something like this


问:
questions on aggregation functions
I am trying to roll up/aggregate the records but cannot find the solution from oracle aggregation functions.

I've been playing with LAG, COLLECT, RANK, but couldn't find a solution yet.

I have the following table and would need to pull the last 5 user comments for the last two user actions.

From below sample, last two actions are Action2 and Action3.

```<code>date     | user_id | user_action | user_comment
---------+---------+-------------+-------------
5/1/2019 | USER3   | OPEN        | COMMENT0
5/1/2019 | USER1   | ACTION1     | COMMENT1
5/2/2019 | USER2   | OPEN        | COMMENT2
5/3/2019 | USER2   | ACTION2     | COMMENT3
5/4/2019 | USER3   | OPEN        | COMMENT4
5/5/2019 | USER3   | OPEN        | COMMENT5
5/5/2019 | USER4   | OPEN        | COMMENT6
5/6/2019 | USER3   | OPEN        | COMMENT7
5/7/2019 | USER3   | OPEN        | COMMENT8
5/8/2019 | USER3   | OPEN        | COMMENT9
5/9/2019 | USER3   | ACTION3     | COMMENT10
</code>```

The point is  that User4's action should not be included.

Comment0 should not be included as it's not between Action2 and action3 even though it's the same user as Action3.

Expected results:

```<code>user_id | action  | comments
--------+---------+--------------------------------------------------
USER3   | ACTION3 | COMMENT10//COMMENT9//COMMENT8//COMMENT7//COMMENT5
USER2   | ACTION2 | COMMENT3//COMMENT2
</code>```

Can anyone provide any tips?

答:
The following query may need some tweaking.  However, it can give you a starting point for finding a solution that
fits your requirements.  Ideas/steps: {1} Number all entries for a particular user via ROW_NUMBER(). {2} Find the last 2 actions. {3} join the 2 result sets, pick the last 5 entries, and get the comments into one row by using GROUP BY and LISTAGG().

```<code>select
  UA.userid, UA.useraction
, listagg( R.usercomment, '//' ) within group ( order by R.date_ desc ) --{3}
  as comments
from (
  select -- {1}
    date_, userid, useraction, usercomment
  , row_number() over ( partition by userid order by date_ desc ) rownum_
  from useractions
) R join ( -- {3}
  select userid, useraction -- {2}
  from (
    select date_, userid, useraction
    , row_number() over ( order by date_ desc ) rownum2_
    from useractions
    where useraction like 'ACTION%'
  )
  where rownum2_ <= 2
) UA on R.userid = UA.userid      -- {3} join
where R.rownum_ between 1 and 5   -- {3} we only the last 5 entries
group by UA.userid, UA.useraction -- {3}
order by userid desc
;

-- result
USERID  USERACTION  COMMENTS
USER3   ACTION3     COMMENT10//COMMENT9//COMMENT8//COMMENT7//COMMENT5
USER2   ACTION2     COMMENT3//COMMENT2
</code>```

DBfiddle

Title: questions on aggregation functions

Body:
I am trying to roll up/aggregate the records but cannot find the solution from oracle aggregation functions.

I've been playing with LAG, COLLECT, RANK, but couldn't find a solution yet.

I have the following table and would need to pull the last 5 user comments for the last two user actions.

From below sample, last two actions are Action2 and Action3.

date     | user_id | user_action | user_comment
---------+---------+-------------+-------------
5/1/2019 | USER3   | OPEN        | COMMENT0
5/1/2019 | USER1   | ACTION1     | COMMENT1
5/2/2019 | USER2   | OPEN        | COMMENT2
5/3/2019 | USER2   | ACTION2     | COMMENT3
5/4/2019 | USER3   | OPEN        | COMMENT4
5/5/2019 | USER3   | OPEN        | COMMENT5
5/5/2019 | USER4   | OPEN        | COMMENT6
5/6/2019 | USER3   | OPEN        | COMMENT7
5/7/2019 | USER3   | OPEN        | COMMENT8
5/8/2019 | USER3   | OPEN        | COMMENT9
5/9/2019 | USER3   | ACTION3     | COMMENT10

The point is  that User4's action should not be included.

Comment0 should not be included as it's not between Action2 and action3 even though it's the same user as Action3.

Expected results:

user_id | action  | comments
--------+---------+--------------------------------------------------
USER3   | ACTION3 | COMMENT10//COMMENT9//COMMENT8//COMMENT7//COMMENT5
USER2   | ACTION2 | COMMENT3//COMMENT2

Can anyone provide any tips?

Body:
The following query may need some tweaking.  However, it can give you a starting point for finding a solution that
fits your requirements.  Ideas/steps: {1} Number all entries for a particular user via ROW_NUMBER(). {2} Find the last 2 actions. {3} join the 2 result sets, pick the last 5 entries, and get the comments into one row by using GROUP BY and LISTAGG().

select
  UA.userid, UA.useraction
, listagg( R.usercomment, '//' ) within group ( order by R.date_ desc ) --{3}
  as comments
from (
  select -- {1}
    date_, userid, useraction, usercomment
  , row_number() over ( partition by userid order by date_ desc ) rownum_
  from useractions
) R join ( -- {3}
  select userid, useraction -- {2}
  from (
    select date_, userid, useraction
    , row_number() over ( order by date_ desc ) rownum2_
    from useractions
    where useraction like 'ACTION%'
  )
  where rownum2_ <= 2
) UA on R.userid = UA.userid      -- {3} join
where R.rownum_ between 1 and 5   -- {3} we only the last 5 entries
group by UA.userid, UA.useraction -- {3}
order by userid desc
;

-- result
USERID  USERACTION  COMMENTS
USER3   ACTION3     COMMENT10//COMMENT9//COMMENT8//COMMENT7//COMMENT5
USER2   ACTION2     COMMENT3//COMMENT2

DBfiddle


问:
SciChart AxesPanelTemplate with dynamic grid
my task is to draw a flexible number of digital signal realtime-data in SciChart.
Due to the nature of this signals they are between 0..1. I want to have them stacked as in the SciChart example found at https://www.scichart.com/example/wpf-chart-example-vertically-stacked-yaxis/.
But with a dynamic grid template inside the YAxesPanelTemplate. What ever I try, there are no YAxes drawn.

I'm using a GridExtension which is very close to the one found here:
https://rachel53461.wordpress.com/2011/09/17/wpf-grids-rowcolumn-count-properties/
refernced from this answer
https://rachel53461.wordpress.com/2011/09/17/wpf-grids-rowcolumn-count-properties/

Any help is highly appreciated

Cheers

Martin

答:
my solution might not be ideal, but it is almost working for me.
Since I’m developing the code for a customer, I’m not allowed to post code by NDA, but I can give my theoretical approach.

specify the number of YAxes in VM

use this to build the grid inside ItemPanelTemplate and bind with DynamicResource (see example in link below)

to do so, use class from this blog and adopt as needed. I build
a specialized class for my use-case

bind to the SizeChangedEvent of RenderSurface Iterate the axes from
YAxes,calculate height per axis and set it.

inside the same loop don’t forget to set the row by using
Grid.SetRow(axis, rowIndex)

This approach is from my point of view not the most performing, but the only I was able to discover from the SciChart docs.

The last task which I’m facing, is to get the height of the chart portion of the RenderSurface, as the height given in SizeChanged is of the full height including YAxis and other stuff drawn.

Maybe someone from SciChart (@Dr. ABT - just maybe) can help out on this last task?

Hope this helps someone else too.

Cheers

Martin


问:
Executing a Command Getting OS version prints two times while using script, but it actually prints one time while executing manual
I executed below command in  RHEL6.10
'''
./tqreclist -s server -t HINV.Summary | awk -F, '{print $4}'
'''
when I execute it manually, I am getting OS version printed in my screen, either Linux or Windows.

But When I execute the same command in bash script, I am getting the same version printed twice, like Linux Linux, Windows Windows.

I thought something bad in my code, So I examined it properly, Immediately after executing the above command, I noticed it prints duplicate value in screen so I changed from awk to cut, but I am getting the same results.
Could someone please help me what would be wrong?

```<code>a=$(./tqreclist -s server -t HINV.Summary | awk -F, '{print $4}')

echo $a

</code>```

I expect it should print actual value, rather then, it is now printing two value, which is duplicate of one.

答:
I tried to reproduce your problem as follows, but it works correctly for me:

```<code>$ a=$(echo "1,2,3,4,5,6,7" | awk -F, '{print $4}')
$ echo $a
4
</code>```

If you try a test like this yourself and it works correctly, then the issue is most likely with the "tqreclist" file.

Body:
I executed below command in  RHEL6.10
'''
./tqreclist -s server -t HINV.Summary | awk -F, '{print $4}'
'''
when I execute it manually, I am getting OS version printed in my screen, either Linux or Windows.

But When I execute the same command in bash script, I am getting the same version printed twice, like Linux Linux, Windows Windows.

I thought something bad in my code, So I examined it properly, Immediately after executing the above command, I noticed it prints duplicate value in screen so I changed from awk to cut, but I am getting the same results.
Could someone please help me what would be wrong?

a=$(./tqreclist -s server -t HINV.Summary | awk -F, '{print $4}')

echo $a

I expect it should print actual value, rather then, it is now printing two value, which is duplicate of one.

Body:
I tried to reproduce your problem as follows, but it works correctly for me:

$ a=$(echo "1,2,3,4,5,6,7" | awk -F, '{print $4}')
$ echo $a
4

If you try a test like this yourself and it works correctly, then the issue is most likely with the "tqreclist" file.


问:
Google App. Engine - Hosting our Web Application
All,

We are trying to host our web application on Google App. Engine with little success.

Here are the specifics:

<s> The web application is built on HTML5, SVG & Javascript. We are using python 2.6 for upload. We initially used the following tutorial for upload but are getting errors once its uploaded.</s>

Link to tutorial: http://www.labnol.org/internet/host-website-on-google-app-engine/18801/

<s>We are getting errors in the appcfg.py python file. We are totally clueless how to go about using this so any guidance would be awesome, tutorials would be even more so. </s>

UPDATE: Further to the outcry and Milimetric's helpful post, here is more detail:

We have managed to upload the web application onto the Google App Engine. Going into the dashboard, we can see the application is running (we can see the instance graphs and CPU stats), however, when we execute the custom link to the web application, we only get the 'Hello World' message.

We followed the tutorial by Milimetric & Rolled back the 'appcfg.py' to original state. Following the tutorial, we only made changes to the 'app.yaml' (inserted our application name). We didnt write any custom python script.

We are not getting any errors anywhere, only the message 'Hello World' upon executing the link in the browser window.

Hope the above is more useful.

Cheers,

答:
Google app engine is a cloud computing technology and it is designed for developing and hosting web applications it supports APIs, and frameworks. To solve this issue you ha eto understand app engine completely so to learn more about app engine visit the link above:

http://en.wikipedia.org/wiki/Google_App_Engine

ContentLicense: CC BY-SA 3.0


问:
Problem adding datefield to invoice odoo12
The following Python script does not create a date field:</p>

```<code>from datetime import datetime

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError

class DealInvoice(models.Model):
    _inherit = 'account.invoice'

    x_date_deal = fields.Date(string='Date Deal',
                                required=True,
                                readonly=True,
                                default=(date.today()),
                                index=True,
                                states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
                                help='Item date deal.')

    @api.constrains('x_date_deal')
    def _x_date_deal_check(self):
        for record in self:
            if record.x_date_deal and record.x_date_deal [0] <= str(date.today()):
                raise ValidationError(_("Date deal must be before current date."))
</code>```

答:
The code hereunder gives the error 'date not defined'. In the end i just want avalidation that a date is today or not more than 5 days in the past. Thanks for your help.

from odoo import api, fields, models, _
  from odoo.exceptions import ValidationError
  from datetime import date
  today = date.today

class AccountInvoice(models.Model):
      _inherit = 'account.invoice'
      _name = 'account.invoice'

```<code>x_date_deal = fields.Date(string='Date of Deal', required=True, readonly=False, index=True,
                                states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
                                help='Date of Deal')

@api.constrains('x_date_deal')
def _delivery_date_check(self):
    for record in self:
        if record.x_date_deal and record.x_date_deal > today:
            raise ValidationError(_("Deal Date must be ...."))
</code>```

Body:
The following Python script does not create a date field:

from datetime import datetime

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError

class DealInvoice(models.Model):
    _inherit = 'account.invoice'

    x_date_deal = fields.Date(string='Date Deal',
                                required=True,
                                readonly=True,
                                default=(date.today()),
                                index=True,
                                states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
                                help='Item date deal.')

    @api.constrains('x_date_deal')
    def _x_date_deal_check(self):
        for record in self:
            if record.x_date_deal and record.x_date_deal [0] <= str(date.today()):
                raise ValidationError(_("Date deal must be before current date."))

Body:
The code hereunder gives the error 'date not defined'. In the end i just want avalidation that a date is today or not more than 5 days in the past. Thanks for your help.

from odoo import api, fields, models, _
  from odoo.exceptions import ValidationError
  from datetime import date
  today = date.today

class AccountInvoice(models.Model):
      _inherit = 'account.invoice'
      _name = 'account.invoice'

x_date_deal = fields.Date(string='Date of Deal', required=True, readonly=False, index=True,
                                states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
                                help='Date of Deal')

@api.constrains('x_date_deal')
def _delivery_date_check(self):
    for record in self:
        if record.x_date_deal and record.x_date_deal > today:
            raise ValidationError(_("Deal Date must be ...."))


问:
How to read CSV file into 2d array of struct with each element having a determining character (C, G, M) to sort into the struct?
I am trying to create a 2d map of array using the csv input

```<code>   5,4
   ,,,C 200
   ,G Vibranium Shield:hands:990,,C 50
   M Healing Potion:85,,M Defence Enchanment:360,
   ,,,
   ,,G Lighsaber:hands:850,5,4
</code>```

The first row is the size of the array given.

The problem I am having right now is how to still count the empty list in the csv as a row and column in the array such as ",,,". Plus, how to read the determining character (C, G, M) in order to store the element in the struct. Example, G Vibranium Shield:hands:990, G will be the determining character stored in char type which then i use the switch case to store other element into the appropriate struct.

I tried to use fgets() strtok() but I can't read separately the determining element from other element in the CSV. As from other example it seem it need prior knowledge into which element will be in the line and predetermine the read line and not based on the determining character in the CSV. Thus I used fscanf to read:

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

typedef struct map
{
char types;
char geartypes[100];
int coins;
int values;
char items[100];
}map;

struct map **m;

int main()
{
    FILE* mapz;
    int i,j,h;
    int width,height;
    char a;
    mapz=fopen("map.csv","r");

    if(mapz!=NULL)
    {
        fscanf(mapz,"%d,%d",&height,&width);
        map **m=(map **)malloc(height * sizeof(map *));
        for(i=0;i<height;i++)
        {
            m[i]=(map*)malloc(width * sizeof(map));
        }
        for(h=0;h<height;h++)
        {
            for(j=0;j<width;j++)
            {
                fscanf(mapz,"%c",&a);
                switch(a)
                {
                case('C'):
                    m[h][j].types=a;
                    fscanf(mapz,"%d",&m[h][j].coins);
                    break;
                case('G'):
                    m[h][j].types=a;
                    fscanf(mapz,"%[^,:]s",m[h][j].items);
                    fscanf(mapz,"%[^,:]s",m[h][j].geartypes);
                    fscanf(mapz,"%d",&m[h][j].values);
                    break;
                case('M'):
                    m[h][j].types=a;
                    fscanf(mapz,"%[^,:]s",m[h][j].items);
                    fscanf(mapz,"%d",&m[h][j].values);
                    break;
                }

            }
        }
        for(h=0;h<height;h++)
        {
            for(j=0;j<width;j++)
            {
                switch(m[h][j].types)
                {
                case('C'):
                    printf("%c",m[h][j].types);
                    printf("%d\n",m[h][j].coins);
                    break;
                case('G'):
                    printf("%c",m[h][j].types);
                    printf("%s%s%d\n",m[h][j].items,m[h][j].geartypes,m[h][j].values);
                    break;
                case('M'):
                    printf("%c",m[h][j].types);
                    printf("%s%d\n",m[h][j].items,m[h][j].values);
                    break;
                }
            }
        }
    }
    else
    {
        printf("No such file in directory");
    }
    fclose(mapz);
    return 0;
</code>```

I tried to use fscanf but it seem to also read the "," which messed up the for count. When i ran the code it come out blank.

答:
Since you are stuck on handling empty fields when you are tokenizing each line, let's look at using strsep to handle that for you. There are a few caveats about using strsep. First note the type of the first parameter. It is char **. That means you cannot read each line into a fixed character array and pass the address of a fixed array (it would not be char**, but instead char (*)[length]). Next, since strsep will update the pointer provided as the first parameter, you cannot simply give it the address of the allocated buffer you are using to store each line you read (you would lose the pointer to the start of the allocated block and be unable to free() the memory or read more than one line.

So, bottom line, you need an allocated buffer to hold the text you are going to pass to strsep, and then your need 2 pointers, one to capture the return from strsep and one to pass the address of to strsep (to allow you to preserve your original buffer pointer).

With that in mind, you can parse your CSV with empty fields similar to:

```<code>    while (fgets (buf, MAXC, fp)) { /* read each line in file */
        size_t i = 0;       /* counter */
        p = fields = buf;   /* initialize pointers to use with strsep */
        printf ("\nline %2zu:\n", n++ + 1);         /* output heading */
        while ((p = strsep (&fields, DELIM))) {     /* call strsep */
            p[strcspn(p, "\r\n")] = 0;              /* trim '\n' (last) */
            printf ("  field %2zu: '%s'\n", i++ + 1, p); /* output field */
        }
    }
</code>```

Putting that together in a full example using your data, you can do something similar to:

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

#define MAXC  1024      /* if you need a constant, #define one (or more) */
#define DELIM ","       /* (numeric or string) */

int main (int argc, char **argv) {

    size_t n = 0, lines, nflds;
    char *buf, *fields, *p; /* must use 2 pointers for strsep */
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    if (!(buf = malloc (MAXC))) {   /* allocate storage for buffer */
        perror ("malloc-buf");      /* cannot be array with strsep */
        return 1;
    }

    if (!fgets (buf, MAXC, fp)) {   /* read/validate 1st line */
        fputs ("error: insufficient input line 1.\n", stderr);
        return 1;
    }   /* convert to lines and no. of fields (lines not needed) */
    if (sscanf (buf, "%zu,%zu", &lines, &nflds) != 2) {
        fputs ("error: invalid format line 1.\n", stderr);
        return 1;
    }

    while (fgets (buf, MAXC, fp)) { /* read each line in file */
        size_t i = 0;       /* counter */
        p = fields = buf;   /* initialize pointers to use with strsep */
        printf ("\nline %2zu:\n", n++ + 1);         /* output heading */
        while ((p = strsep (&fields, DELIM))) {     /* call strsep */
            p[strcspn(p, "\r\n")] = 0;              /* trim '\n' (last) */
            printf ("  field %2zu: '%s'\n", i++ + 1, p); /* output field */
        }
    }
    if (fp != stdin) fclose (fp);   /* close file if not stdin */
    free (buf);  /* free allocated memory */

    return 0;
}
</code>```

Example Input File

```<code>$ cat dat/emptyflds.csv
5,4
,,,C 200
,G Vibranium Shield:hands:990,,C 50
M Healing Potion:85,,M Defence Enchanment:360,
,,,
,,G Lighsaber:hands:850,5,4
</code>```

Example Use/Output

The example simply prints the line number and then each separated field on a separate line below it so you can confirm the separation:

```<code>$ ./bin/strcspnsepcsv <dat/emptyflds.csv

line  1:
  field  1: ''
  field  2: ''
  field  3: ''
  field  4: 'C 200'

line  2:
  field  1: ''
  field  2: 'G Vibranium Shield:hands:990'
  field  3: ''
  field  4: 'C 50'

line  3:
  field  1: 'M Healing Potion:85'
  field  2: ''
  field  3: 'M Defence Enchanment:360'
  field  4: ''

line  4:
  field  1: ''
  field  2: ''
  field  3: ''
  field  4: ''

line  5:
  field  1: ''
  field  2: ''
  field  3: 'G Lighsaber:hands:850'
  field  4: '5'
  field  5: '4'
</code>```

(note: line 5 contains a 5th field that exceeds expected no. of fields)

To handle further separation within the fields on ':' or whatever else you need, you are free to call strtok on the pointer p within the field tokenization while loop.

Body:
I am trying to create a 2d map of array using the csv input

   5,4
   ,,,C 200
   ,G Vibranium Shield:hands:990,,C 50
   M Healing Potion:85,,M Defence Enchanment:360,
   ,,,
   ,,G Lighsaber:hands:850,5,4

The first row is the size of the array given.

The problem I am having right now is how to still count the empty list in the csv as a row and column in the array such as ",,,". Plus, how to read the determining character (C, G, M) in order to store the element in the struct. Example, G Vibranium Shield:hands:990, G will be the determining character stored in char type which then i use the switch case to store other element into the appropriate struct.

I tried to use fgets() strtok() but I can't read separately the determining element from other element in the CSV. As from other example it seem it need prior knowledge into which element will be in the line and predetermine the read line and not based on the determining character in the CSV. Thus I used fscanf to read:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct map
{
char types;
char geartypes[100];
int coins;
int values;
char items[100];
}map;

struct map **m;

int main()
{
    FILE* mapz;
    int i,j,h;
    int width,height;
    char a;
    mapz=fopen("map.csv","r");

    if(mapz!=NULL)
    {
        fscanf(mapz,"%d,%d",&height,&width);
        map **m=(map **)malloc(height * sizeof(map *));
        for(i=0;i<height;i++)
        {
            m[i]=(map*)malloc(width * sizeof(map));
        }
        for(h=0;h<height;h++)
        {
            for(j=0;j<width;j++)
            {
                fscanf(mapz,"%c",&a);
                switch(a)
                {
                case('C'):
                    m[h][j].types=a;
                    fscanf(mapz,"%d",&m[h][j].coins);
                    break;
                case('G'):
                    m[h][j].types=a;
                    fscanf(mapz,"%[^,:]s",m[h][j].items);
                    fscanf(mapz,"%[^,:]s",m[h][j].geartypes);
                    fscanf(mapz,"%d",&m[h][j].values);
                    break;
                case('M'):
                    m[h][j].types=a;
                    fscanf(mapz,"%[^,:]s",m[h][j].items);
                    fscanf(mapz,"%d",&m[h][j].values);
                    break;
                }

            }
        }
        for(h=0;h<height;h++)
        {
            for(j=0;j<width;j++)
            {
                switch(m[h][j].types)
                {
                case('C'):
                    printf("%c",m[h][j].types);
                    printf("%d\n",m[h][j].coins);
                    break;
                case('G'):
                    printf("%c",m[h][j].types);
                    printf("%s%s%d\n",m[h][j].items,m[h][j].geartypes,m[h][j].values);
                    break;
                case('M'):
                    printf("%c",m[h][j].types);
                    printf("%s%d\n",m[h][j].items,m[h][j].values);
                    break;
                }
            }
        }
    }
    else
    {
        printf("No such file in directory");
    }
    fclose(mapz);
    return 0;

I tried to use fscanf but it seem to also read the "," which messed up the for count. When i ran the code it come out blank.

Body:
Since you are stuck on handling empty fields when you are tokenizing each line, let's look at using strsep to handle that for you. There are a few caveats about using strsep. First note the type of the first parameter. It is char **. That means you cannot read each line into a fixed character array and pass the address of a fixed array (it would not be char**, but instead char (*)[length]). Next, since strsep will update the pointer provided as the first parameter, you cannot simply give it the address of the allocated buffer you are using to store each line you read (you would lose the pointer to the start of the allocated block and be unable to free() the memory or read more than one line.

So, bottom line, you need an allocated buffer to hold the text you are going to pass to strsep, and then your need 2 pointers, one to capture the return from strsep and one to pass the address of to strsep (to allow you to preserve your original buffer pointer).

With that in mind, you can parse your CSV with empty fields similar to:

    while (fgets (buf, MAXC, fp)) { /* read each line in file */
        size_t i = 0;       /* counter */
        p = fields = buf;   /* initialize pointers to use with strsep */
        printf ("\nline %2zu:\n", n++ + 1);         /* output heading */
        while ((p = strsep (&fields, DELIM))) {     /* call strsep */
            p[strcspn(p, "\r\n")] = 0;              /* trim '\n' (last) */
            printf ("  field %2zu: '%s'\n", i++ + 1, p); /* output field */
        }
    }

Putting that together in a full example using your data, you can do something similar to:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXC  1024      /* if you need a constant, #define one (or more) */
#define DELIM ","       /* (numeric or string) */

int main (int argc, char **argv) {

    size_t n = 0, lines, nflds;
    char *buf, *fields, *p; /* must use 2 pointers for strsep */
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    if (!(buf = malloc (MAXC))) {   /* allocate storage for buffer */
        perror ("malloc-buf");      /* cannot be array with strsep */
        return 1;
    }

    if (!fgets (buf, MAXC, fp)) {   /* read/validate 1st line */
        fputs ("error: insufficient input line 1.\n", stderr);
        return 1;
    }   /* convert to lines and no. of fields (lines not needed) */
    if (sscanf (buf, "%zu,%zu", &lines, &nflds) != 2) {
        fputs ("error: invalid format line 1.\n", stderr);
        return 1;
    }

    while (fgets (buf, MAXC, fp)) { /* read each line in file */
        size_t i = 0;       /* counter */
        p = fields = buf;   /* initialize pointers to use with strsep */
        printf ("\nline %2zu:\n", n++ + 1);         /* output heading */
        while ((p = strsep (&fields, DELIM))) {     /* call strsep */
            p[strcspn(p, "\r\n")] = 0;              /* trim '\n' (last) */
            printf ("  field %2zu: '%s'\n", i++ + 1, p); /* output field */
        }
    }
    if (fp != stdin) fclose (fp);   /* close file if not stdin */
    free (buf);  /* free allocated memory */

    return 0;
}

Example Input File

$ cat dat/emptyflds.csv
5,4
,,,C 200
,G Vibranium Shield:hands:990,,C 50
M Healing Potion:85,,M Defence Enchanment:360,
,,,
,,G Lighsaber:hands:850,5,4

Example Use/Output

The example simply prints the line number and then each separated field on a separate line below it so you can confirm the separation:

$ ./bin/strcspnsepcsv <dat/emptyflds.csv

line  1:
  field  1: ''
  field  2: ''
  field  3: ''
  field  4: 'C 200'

line  2:
  field  1: ''
  field  2: 'G Vibranium Shield:hands:990'
  field  3: ''
  field  4: 'C 50'

line  3:
  field  1: 'M Healing Potion:85'
  field  2: ''
  field  3: 'M Defence Enchanment:360'
  field  4: ''

line  4:
  field  1: ''
  field  2: ''
  field  3: ''
  field  4: ''

line  5:
  field  1: ''
  field  2: ''
  field  3: 'G Lighsaber:hands:850'
  field  4: '5'
  field  5: '4'

(note: line 5 contains a 5th field that exceeds expected no. of fields)

To handle further separation within the fields on ':' or whatever else you need, you are free to call strtok on the pointer p within the field tokenization while loop.


问:
Django don't show first image in template
I'm new to Django and I need to show all images inside different folders in the HTML file.

In views.py I have something like this:

```<code>python
        template = loader.get_template('index.html')
        context = {
            'images': imm,
        }
        return HttpResponse(template.render(context, request))
</code>```

imm is a variable that contains path of some images.
In the template I have:

```<code>html
<div class="row">
   {{ images }}
   {% for image in images %}
   <div class="column">
       <img src="{{ image }}" style="width:100%" >
       {{ image }}
       </div>
   {% endfor %}

</div>
</code>```

In here the first image is not showed while the others are OK. It is not a problem of the image itself because i tried to change the order of the images in images list.

{{ image }} returns the right path of the image but when I see the code through the browser the first image has path "".

{{ images }} is:

```<code>['/path/000000000115.jpg', '/path/000000000139.jpg', '/path/000000000140.jpg', '/path/000000000632.jpg', '/path/000000000724.jpg', '/path/000000000776.jpg', '/path/000000000785.jpg']
</code>```

I'm not understanding what is wrong.
Thanks in advance.

答:
Ok, I solved adding:

```<code>HTML
<img src="" style="width:100% display:none">

</code>```

before the

```<code>{% for image in images %}
</code>```

Body:
I'm new to Django and I need to show all images inside different folders in the HTML file.

In views.py I have something like this:

python
        template = loader.get_template('index.html')
        context = {
            'images': imm,
        }
        return HttpResponse(template.render(context, request))

imm is a variable that contains path of some images.
In the template I have:

html

   {{ images }}
   {% for image in images %}

       {{ image }}

   {% endfor %}

In here the first image is not showed while the others are OK. It is not a problem of the image itself because i tried to change the order of the images in images list.

{{ image }} returns the right path of the image but when I see the code through the browser the first image has path "".

{{ images }} is:

['/path/000000000115.jpg', '/path/000000000139.jpg', '/path/000000000140.jpg', '/path/000000000632.jpg', '/path/000000000724.jpg', '/path/000000000776.jpg', '/path/000000000785.jpg']

I'm not understanding what is wrong.
Thanks in advance.

Body:
Ok, I solved adding:

HTML
<img src="" style="width:100% display:none">

before the

{% for image in images %}


问:
SQLKata Dynamic Where Clause
I am using SQLKata to build a SQL statement in C# and found some code posted on the Github forum but it does not compile.  I need help getting it to compile.

I am receiving two errors on this line query.Where(q =>

Compilation error (line 17, col 16): Not all code paths return a value in lambda expression of type 'System.Func'

Compilation error (line 17, col 16): Cannot convert lambda expression to type 'object' because it is not a delegate type

```<code>class Group
{
   public List<Condition> Conditions {get; set;}
}

class Condition
{
   public string Field {get; set;}
   public string Operator {get; set;}
   public object Value {get; set;}
}

var query = new Query("Countries");

foreach(Group group in groups)
{
    query.Where(q =>
    {
        foreach(Condition c in group.Conditions)
        {
            q.OrWhere(c.Field, c.Operator, c.Value);
        }
    });
}
</code>```

.NET Fiddle is here

Github Post here

UPDATE
I've updated the fiddle based on Alex's answer.  I was looking for a clause, so the expected output is to have the OR statements surrounded by parenthesis.  It's mostly working now as expected except  each group should be within it's own parens, like below:

SELECT * FROM [Countries] WHERE ([Group1Field1] = @p0 OR [Group1Field2] > @p1 OR [Group1Field3] < @p2 OR [Group1Field4] = @p3) OR ([Group2Field1] = @p4 OR [Group2Field2] >= @p5 OR [Group2Field3] <= @p6) AND [Id] = @p7

Final Update
Figured it out.  Gives the above expected output.  Thanks.

```<code>var query = new Query("Countries");

    foreach (Group group in groups)
    {
        query.OrWhere(q => {
        foreach (Condition c in group.Conditions)
        {
            q.OrWhere(c.Field, c.Operator, c.Value);
        }
        return q;

        });

    }
query.Where("Id", "=", 10);
</code>```

答:
Try this:

```<code>List<Group> groups = new List<Group>
{
    new Group
    {
        Conditions = new List<Condition>
        {
            new Condition {Field = "Group1Field1", Operator = "=", Value="Group1Value1"},
            new Condition {Field = "Group1Field2", Operator = ">", Value="Group1Value2"},
            new Condition {Field = "Group1Field3", Operator = "<", Value="Group1Value3"},
            new Condition {Field = "Group1Field4", Operator = "=", Value="Group1Value4"}
        }
    },
    new Group
    {
        Conditions = new List<Condition>
        {
            new Condition {Field = "Group2Field1", Operator = "=", Value="Group2Value1"},
            new Condition {Field = "Group2Field2", Operator = ">=", Value="Group2Value2"},
            new Condition {Field = "Group2Field3", Operator = "<=", Value="Group2Value3"}
        }
    }
};

var query = new Query("Countries");
foreach (Group group in groups)
    foreach (Condition c in group.Conditions)
        query.OrWhere(c.Field, c.Operator, c.Value);

Console.WriteLine(new SqlServerCompiler().Compile(query).Sql);
</code>```

Output is:

```<code>SELECT * FROM [Countries] WHERE [Group1Field1] = @p0 OR [Group1Field2] > @p1 OR [Group1Field3] < @p2 OR [Group1Field4] = @p3 OR [Group2Field1] = @p4 OR [Group2Field2] >= @p5 OR [Group2Field3] <= @p6
</code>```

.NET Fiddle

Update:

I inspected documentation and tests and didn't found anything better than the following.
To get the output you need use:

```<code>foreach (var group in groups)
{
    if (!group.Conditions.Any())
        continue;

    if (group.Conditions.Count == 1)
    {
        var single = group.Conditions.Single();
        query.OrWhereRaw($"([{single.Field}] {single.Operator} ?)", single.Value);
        continue;
    }

    var first = group.Conditions.First();
    var last = group.Conditions.Last();
    var others = group.Conditions.Skip(1).Take(group.Conditions.Count - 2);

    query.OrWhereRaw($"([{first.Field}] {first.Operator} ?", first.Value);
    foreach (var c in others)
        query.OrWhere(c.Field, c.Operator, c.Value);
    query.OrWhereRaw($"[{last.Field}] {last.Operator} ?)", last.Value);
}

query.Where("Id", "=", 10);
</code>```

instead of:

```<code>foreach (Group group in groups)
    foreach (Condition c in group.Conditions)
        query.OrWhere(c.Field, c.Operator, c.Value);
</code>```

.NETFiddle

Title: SQLKata Dynamic Where Clause

Body:
I am using SQLKata to build a SQL statement in C# and found some code posted on the Github forum but it does not compile.  I need help getting it to compile.

I am receiving two errors on this line query.Where(q =>

Compilation error (line 17, col 16): Not all code paths return a value in lambda expression of type 'System.Func'

Compilation error (line 17, col 16): Cannot convert lambda expression to type 'object' because it is not a delegate type

class Group
{
   public List<Condition> Conditions {get; set;}
}

class Condition
{
   public string Field {get; set;}
   public string Operator {get; set;}
   public object Value {get; set;}
}

var query = new Query("Countries");

foreach(Group group in groups)
{
    query.Where(q =>
    {
        foreach(Condition c in group.Conditions)
        {
            q.OrWhere(c.Field, c.Operator, c.Value);
        }
    });
}

.NET Fiddle is here

Github Post here

UPDATE
I've updated the fiddle based on Alex's answer.  I was looking for a clause, so the expected output is to have the OR statements surrounded by parenthesis.  It's mostly working now as expected except  each group should be within it's own parens, like below:

SELECT * FROM [Countries] WHERE ([Group1Field1] = @p0 OR [Group1Field2] > @p1 OR [Group1Field3] < @p2 OR [Group1Field4] = @p3) OR ([Group2Field1] = @p4 OR [Group2Field2] >= @p5 OR [Group2Field3] <= @p6) AND [Id] = @p7

Final Update
Figured it out.  Gives the above expected output.  Thanks.

var query = new Query("Countries");

    foreach (Group group in groups)
    {
        query.OrWhere(q => {
        foreach (Condition c in group.Conditions)
        {
            q.OrWhere(c.Field, c.Operator, c.Value);
        }
        return q;

        });

    }
query.Where("Id", "=", 10);

Body:
Try this:

List<Group> groups = new List<Group>
{
    new Group
    {
        Conditions = new List<Condition>
        {
            new Condition {Field = "Group1Field1", Operator = "=", Value="Group1Value1"},
            new Condition {Field = "Group1Field2", Operator = ">", Value="Group1Value2"},
            new Condition {Field = "Group1Field3", Operator = "<", Value="Group1Value3"},
            new Condition {Field = "Group1Field4", Operator = "=", Value="Group1Value4"}
        }
    },
    new Group
    {
        Conditions = new List<Condition>
        {
            new Condition {Field = "Group2Field1", Operator = "=", Value="Group2Value1"},
            new Condition {Field = "Group2Field2", Operator = ">=", Value="Group2Value2"},
            new Condition {Field = "Group2Field3", Operator = "<=", Value="Group2Value3"}
        }
    }
};

var query = new Query("Countries");
foreach (Group group in groups)
    foreach (Condition c in group.Conditions)
        query.OrWhere(c.Field, c.Operator, c.Value);

Console.WriteLine(new SqlServerCompiler().Compile(query).Sql);

Output is:

SELECT * FROM [Countries] WHERE [Group1Field1] = @p0 OR [Group1Field2] > @p1 OR [Group1Field3] < @p2 OR [Group1Field4] = @p3 OR [Group2Field1] = @p4 OR [Group2Field2] >= @p5 OR [Group2Field3] <= @p6

.NET Fiddle

Update:

I inspected documentation and tests and didn't found anything better than the following.
To get the output you need use:

foreach (var group in groups)
{
    if (!group.Conditions.Any())
        continue;

    if (group.Conditions.Count == 1)
    {
        var single = group.Conditions.Single();
        query.OrWhereRaw($"([{single.Field}] {single.Operator} ?)", single.Value);
        continue;
    }

    var first = group.Conditions.First();
    var last = group.Conditions.Last();
    var others = group.Conditions.Skip(1).Take(group.Conditions.Count - 2);

    query.OrWhereRaw($"([{first.Field}] {first.Operator} ?", first.Value);
    foreach (var c in others)
        query.OrWhere(c.Field, c.Operator, c.Value);
    query.OrWhereRaw($"[{last.Field}] {last.Operator} ?)", last.Value);
}

query.Where("Id", "=", 10);

instead of:

foreach (Group group in groups)
    foreach (Condition c in group.Conditions)
        query.OrWhere(c.Field, c.Operator, c.Value);

.NETFiddle


问:
merge sort in place report index out of range error
I mimic from the answer https://stackoverflow.com/a/19086076/10892923 of an inplace merge sort   as

```<code>import unittest
import logging

logging.basicConfig(level=logging.DEBUG, format="%(levelname)s　%(message)s")

#in-place merge sort
def merge_inplace(A, start, mid, end) -> "None":
    left = A[start:mid]
    right = A[mid:end]
    i = 0
    j = 0

    for c in range(start,end): #c for cur
        if (i < len(left) and left[i] <= right[j]) or i >= len(right):
            A[c] = left[i]
            i = i + 1
        else:
            A[c] = right[j]
            j = j + 1

def mergeSort_inplace(A, lo, hi) -> "None":
    if lo < hi - 1:
        mid = (lo + hi) // 2
        mergeSort_inplace(A,lo,mid)
        mergeSort_inplace(A,mid,hi)
        merge_inplace(A, lo, mid, hi)

class MyCase(unittest.TestCase):
    def test_a(self):
        A  = [20, 30, 21, 15, 42, 45, 31, 0, 9]
        mergeSort_inplace(A,0,len(A))
        print(A)

unittest.main()
</code>```

I double checked the logic and assert that it very clear,

it reported error otherwise.

```<code>ERROR: test_a (__main__.MyCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "mergeSort.py", line 31, in test_a
    mergeSort_inplace(A,0,len(A))
  File "mergeSort.py", line 24, in mergeSort_inplace
    mergeSort_inplace(A,lo,mid)
  File "mergeSort.py", line 24, in mergeSort_inplace
    mergeSort_inplace(A,lo,mid)
  File "mergeSort.py", line 26, in mergeSort_inplace
    merge_inplace(A, lo, mid, hi)
  File "mergeSort.py", line 15, in merge_inplace
    A[c] = left[i]
IndexError: list index out of range

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
</code>```

I cannot locate the error why it report list index out of range.

答:
You encountered a short-circuit problem,

Change

```<code> if (i < len(left) and left[i] <= right[j]) or j >= len(right):
</code>```

to

```<code>if j >= len(right) or (i < len(left) and left[i] <= right[j]):
</code>```

More details please refer to  python - Bug with logic operator "or"? - Stack Overflow

and Built-in Types — Python 3.7.3 documentation

Body:
I mimic from the answer https://stackoverflow.com/a/19086076/10892923 of an inplace merge sort   as

import unittest
import logging

logging.basicConfig(level=logging.DEBUG, format="%(levelname)s　%(message)s")

#in-place merge sort
def merge_inplace(A, start, mid, end) -> "None":
    left = A[start:mid]
    right = A[mid:end]
    i = 0
    j = 0

    for c in range(start,end): #c for cur
        if (i < len(left) and left[i] <= right[j]) or i >= len(right):
            A[c] = left[i]
            i = i + 1
        else:
            A[c] = right[j]
            j = j + 1

def mergeSort_inplace(A, lo, hi) -> "None":
    if lo < hi - 1:
        mid = (lo + hi) // 2
        mergeSort_inplace(A,lo,mid)
        mergeSort_inplace(A,mid,hi)
        merge_inplace(A, lo, mid, hi)

class MyCase(unittest.TestCase):
    def test_a(self):
        A  = [20, 30, 21, 15, 42, 45, 31, 0, 9]
        mergeSort_inplace(A,0,len(A))
        print(A)

unittest.main()

I double checked the logic and assert that it very clear,

it reported error otherwise.

ERROR: test_a (__main__.MyCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "mergeSort.py", line 31, in test_a
    mergeSort_inplace(A,0,len(A))
  File "mergeSort.py", line 24, in mergeSort_inplace
    mergeSort_inplace(A,lo,mid)
  File "mergeSort.py", line 24, in mergeSort_inplace
    mergeSort_inplace(A,lo,mid)
  File "mergeSort.py", line 26, in mergeSort_inplace
    merge_inplace(A, lo, mid, hi)
  File "mergeSort.py", line 15, in merge_inplace
    A[c] = left[i]
IndexError: list index out of range

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

I cannot locate the error why it report list index out of range.

Body:
You encountered a short-circuit problem,

Change

 if (i < len(left) and left[i] <= right[j]) or j >= len(right):

to

if j >= len(right) or (i < len(left) and left[i] <= right[j]):

More details please refer to  python - Bug with logic operator "or"? - Stack Overflow

and Built-in Types — Python 3.7.3 documentation


问:
sudo npm install webpack -g (failed)
Run sudo npm install webpack -g, the message shows it works.

 When I type webpack -v, shows"webpack: command not found".

 Node version: 10.15.3

Command:

node install

Output:

node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp WARN Pre-built binaries not installable for fsevents@1.2.9 and node@10.15.3 (node-v64 ABI, unknown) (falling back to source compile with node-gyp)
node-pre-gyp WARN Hit error EACCES: permission denied, mkdir '/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/lib'
gyp WARN EACCES user "root" does not have permission to access the dev dir "/Users/userfile/.node-gyp/10.15.3"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/.node-gyp"
gyp WARN install got an error, rolling back install
gyp WARN install got an error, rolling back install
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/.node-gyp'
gyp ERR! System Darwin 17.7.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node" "--module_name=fse" "--module_path=/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64" "--napi_version=3" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v64"
gyp ERR! cwd /Users/userfile/lib/node_modules/webpack/node_modules/fsevents
gyp ERR! node -v v10.15.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node --module_name=fse --module_path=/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64 --napi_version=3 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:189:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:970:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
node-pre-gyp ERR! System Darwin 17.7.0
node-pre-gyp ERR! command "/usr/local/bin/node" "/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/node_modules/node-pre-gyp/bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /Users/userfile/lib/node_modules/webpack/node_modules/fsevents
node-pre-gyp ERR! node -v v10.15.3
node-pre-gyp ERR! node-pre-gyp -v v0.12.0
node-pre-gyp ERR! not ok
Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node --module_name=fse --module_path=/Users/userfile/lib/node_modules/webpack/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64 --napi_version=3 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/webpack/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 install: `node install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

+ webpack@4.32.2
added 750 packages from 951 contributors in 246.511
```

答:
You've got an EACCESS error, which means that your npm needs more permissions to work correctly.

To grant more rights to npm use this command => sudo chown -R $USER:$USER /your/path/to/node_modules.

If it's not working add also => sudo chmod -R 755 /your/path/to.

It should allows you to use npm w/ sudo.

If you want to do it with another way, here's an article from npm.

Title: sudo npm install webpack -g (failed)


问:
Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead
i am new to react , it would be great if someone can explain the problem , this question has been answered but i am still confused .

```<code>import React from 'react' ;
import Card from './Card.js';
const CardList = ({Friends}) =>{
    const Cardcomponent = Friends.map((user , i) => {
        return(
            <div>
                 <Card id={Friends[i].id} name={Friends[i].name} username={Friends[i].username} instagram={Friends[i].instagram}  />
            </div>
              )
    })
return(
          <div>
                {Cardcomponent}
          </div>
      )
}
export default CardList ;
</code>```

Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

答:
Cardcomponent is a list of components. So to display them, as the error message is telling you, you have to loop over them using map

```<code>{Cardcomponent.map((component, index) => {
  return (
    <div key={index}>
      {component}
    </div>
  )
}
</code>```

Body:
i am new to react , it would be great if someone can explain the problem , this question has been answered but i am still confused .

import React from 'react' ;
import Card from './Card.js';
const CardList = ({Friends}) =>{
    const Cardcomponent = Friends.map((user , i) => {
        return(

                 <Card id={Friends[i].id} name={Friends[i].name} username={Friends[i].username} instagram={Friends[i].instagram}  />

              )
    })
return(

                {Cardcomponent}

      )
}
export default CardList ;

Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

Body:
Cardcomponent is a list of components. So to display them, as the error message is telling you, you have to loop over them using map

{Cardcomponent.map((component, index) => {
  return (
    <div key={index}>
      {component}
    </div>
  )
}


问:
street is not defined error in javascript
I am a beginner in Javascript and I have the following code:

```<code>let address = {
  street: 'Brighton',
  city: 'NY',
  zipcode: 121212,

  showAddress() {
    console.log(street + ' ' + city + ' ' + zipcode);// here is the issue I cannot understand why
  }
}

let address1 = address.showAddress();
</code>```

The above code shows an error

Uncaught ReferenceError: street is not defined
           at Object.showAddress

答:
In the above the {} acts as Object literals not block.There are no variable named street in the scope of showAddress().

You can access it using this which will refer to parent object. According to MDN

When a function is called as a method of an object, its this is set to the object the method is called on

let address = {
  street: 'Brighton',
  city: 'NY',
  zipcode: 121212,

  showAddress() {
    console.log(this.street + ' ' + this.city + ' ' + this.zipcode);// here is the issue I cannot understand why
  }
}

let address1 = address.showAddress(); ```

Body:
I am a beginner in Javascript and I have the following code:

let address = {
  street: 'Brighton',
  city: 'NY',
  zipcode: 121212,

  showAddress() {
    console.log(street + ' ' + city + ' ' + zipcode);// here is the issue I cannot understand why
  }
}

let address1 = address.showAddress();

The above code shows an error

Uncaught ReferenceError: street is not defined
           at Object.showAddress